EJS Template Engine for Express
Last Updated :
29 Feb, 2024
EJS stands for Embedded JavaScript. It is a template engine designed to be used with server-side JavaScript environments like NodeJS and It is used to generate dynamic content in a web page. It simplifies the generation of HTML by allowing you to embed JavaScript code directly in HTML.
In this article, we will learn how to use EJS with its syntax and examples.
How to use EJS?
EJS is a template engine that is used to write JavaScript within HTML to generate dynamic content. EJS file is denoted by .ejs extension. EJS allows you to embed JavaScript code directly within HTML templates using special tags such as <% %> and <%= %>. To use EJS, we have to install it by using the npm install EJS command in our project folder.
Syntax of EJS:
<html>
<head>
<title>EJS Syntax Example</title>
</head>
<body>
<!--Using Variable-->
<h1>Hello, <%= username %>!</h1>
<!--Conditional Statement -->
<% if (isAdmin) { %>
<p>Welcome, Admin!</p>
<% } else { %>
<p>Welcome, User!</p>
<% } %>
<!-- Loop Statement-->
<ul>
<% for(let i=1; i<=5; i++) { %>
<li>Item <%= i %></li>
<% } %>
</ul>
<!-- Include other File-->
<%- include('footer') %>
</body>
</html>
Key Features of EJS Templating Engine:
- It supports variable substitution by using <%= %> tag.
- It supports conditionals and loops directly in the template by using <% %> tag.
- It can be easily used with NodeJS frameworks like ExpressJS.
- It supports reusable components by using include.
Steps to Implement EJS in Express:
Step 1: Create a NodeJS application using the following command:
npm init
Step 2: Install required Dependencies:
npm i ejs express
The updated dependencies in package.json file will look like:
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2"
}
Example: Below is an example to demonstrate the EJS Template Engine for Express.
HTML
< header >
< h1 >Hello From, <%= name %>
</ h1 >
</ header >
|
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title >EJS Example</ title >
< style >
h1 {
color: green;
}
</ style >
</ head >
< body >
<%- include('header') %>
<% if (isAdmin) { %>
< p >Welcome, Admin!</ p >
<% } else { %>
< p >Welcome, User!</ p >
<% } %>
< ul >
<% items.forEach(function(item) { %>
< li >
<%= item %>
</ li >
<% }); %>
</ ul >
</ body >
</ html >
|
Javascript
const express = require( 'express' );
const path = require( 'path' );
const app = express();
const port = 3000;
app.set( 'view engine' , 'ejs' );
app.set( 'views' , path.join(__dirname, 'views' ));
app.get( '/' , (req, res) => {
const data = {
name: 'GeeksForGeeks!' ,
isAdmin: true ,
items: [ 'Apple' , 'Banana' , 'Orange' ,
'Grapes' , 'Mango' ]
};
res.render( 'index' , data);
});
app.listen(port, () => {
console.log(`Server is running at http:
});
|
To run the application use the following command:
node index.js
Output: Now go to http://localhost:3000 in your browser:
Share your thoughts in the comments
Please Login to comment...