Open In App

EJS Template Engine for Express

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




<!-- File path: views/header.ejs -->
<header>
    <!-- Variable Example -->
    <h1>Hello From, <%= name %>
    </h1>
</header>


HTML




<!--File path: views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>EJS Example</title>
    <style>
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
 
    <!-- Include Header File -->
    <%- include('header') %>
 
        <!-- Conditional Example -->
        <% if (isAdmin) { %>
            <p>Welcome, Admin!</p>
            <% } else { %>
                <p>Welcome, User!</p>
                <% } %>
 
                    <!-- Loop Example -->
                    <ul>
                        <% items.forEach(function(item) { %>
                            <li>
                                <%= item %>
                            </li>
                            <% }); %>
                    </ul>
</body>
 
</html>


Javascript




//File path: /index.js (root)
// Import required modules
const express = require('express');
const path = require('path');
 
// Create an Express application
const app = express();
 
// Define the port for the server to listen on
const port = 3000;
 
// Set EJS as the view engine
app.set('view engine', 'ejs');
 
/*
Set the views directory to 'views'
 in the current directory
 */
app.set('views', path.join(__dirname, 'views'));
 
/*
 Define a route to render the Pug
 template when the root path is accessed
 */
app.get('/', (req, res) => {
    //Sending this data from Server
    const data = {
        name: 'GeeksForGeeks!',
        isAdmin: true,
        items: ['Apple', 'Banana', 'Orange',
            'Grapes', 'Mango']
    };
 
    // Render the EJS template named 'index' and pass the data
    res.render('index', data);
});
 
// Start the server and listen on the specified port
app.listen(port, () => {
    // Display a message when the server starts successfully
    console.log(`Server is running at http://localhost:${port}`);
});


To run the application use the following command:

node index.js 

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

ejs-template-output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads