Rendering EJS files with Express.js: A Step-by-Step Guide

Posted by

Rendering EJS File Using Express.js

How to Render EJS File Using Express.js

EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript. Express.js is a popular web framework for Node.js that makes it easy to build web applications. In this article, we will learn how to render an EJS file using Express.js.

Step 1: Install EJS

First, you need to install the EJS package in your Node.js project. You can do this by running the following command in your terminal:

npm install ejs

Step 2: Set up Express.js

Next, you need to set up your Express.js application. Create a new file called app.js and add the following code:


const express = require('express');
const app = express();

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');

app.get('/', (req, res) => {
res.render('index');
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

Step 3: Create an EJS File

Now, create a new folder called views in your project directory. Inside this folder, create a new file called index.ejs and add the following code:

Welcome to EJS

Welcome to EJS Rendering

This is an example of rendering an EJS file using Express.js.

Step 4: Start the Server

Finally, start your Express.js server by running the following command in your terminal:

node app.js

Open your web browser and navigate to http://localhost:3000 to see your EJS file rendered using Express.js.

Congratulations! You have successfully rendered an EJS file using Express.js. You can now customize your EJS files and build dynamic web applications with ease.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x