VOOZH about

URL: https://www.geeksforgeeks.org/node-js/ejs-template-engine-for-express/

⇱ EJS Template Engine for Express - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

EJS Template Engine for Express

Last Updated : 25 Apr, 2026

EJS is a server-side JavaScript template engine for Node.js that enables dynamic HTML generation by embedding JavaScript directly within HTML.

  • Stands for Embedded JavaScript.
  • Used with Node.js and Express.
  • Allows dynamic content rendering in web pages.
  • Embeds JavaScript logic inside HTML templates.

Working with EJS Template Engine

EJS is a template engine that allows embedding JavaScript into HTML to generate dynamic web content.

  • Uses the .ejs file extension.
  • Embeds JavaScript using tags like <% %> and <%= %>.
  • Generates dynamic HTML on the server.
  • Installed via npm install ejs.

Syntax:

<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>

Features

EJS provides powerful features that enable dynamic content generation and seamless integration with server-side JavaScript frameworks.

  • 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 -y

Step 2: Install required Dependencies

 npm install express ejs

Step 3: Set EJS as view engine

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

// Set EJS as view engine
app.set('view engine', 'ejs');

The updated dependencies in package.json file will look like

"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2"
}

To run the application use the following command:

node index.js 

Output: Now go to http://localhost:3000 in your browser

👁 ejs-template-output
  • Express server sends data (name, admin status, items) to the EJS template.
  • EJS template displays content dynamically using that data.
  • Conditional statement shows different messages based on isAdmin.
  • Loop displays all items in a list using forEach().
  • Header file is included using <%- include() %>.
Comment

Explore