Open In App

Use EJS as Template Engine in Node.js

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

EJS (Embedded JavaScript) is a popular templating engine for Node.js that allows you to generate HTML markup with plain JavaScript. It is particularly useful for creating dynamic web pages, as it enables you to embed JavaScript logic directly within your HTML.

EJS

EJS or Embedded Javascript Templating is a templating engine used by Node.js. Template engine helps to create an HTML template with minimal code. Also, it can inject data into an HTML template on the client side and produce the final HTML. EJS is a simple templating language that is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript into HTML pages.

Steps to Use EJS as Template Engine

Installing EJS

To begin with, using EJS as templating engine we need to install EJS using the given command: 

npm install express ejs --save

It will install exxpress and ejs as dependency in the node.js project.

Set Up Your Node Application

JavaScript
// Filename - index.js 

// Set express as Node.js web application
// server framework.

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

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

Create the EJS Template

The default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make a file named “home.ejs” which is to be served on some desired requests in our node project. The content of this page is: 

HTML
<!-- Home.ejs -->

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>

    <style type="text/css" media="screen">
        body {
            background-color: skyblue;
            text-decoration-color: white;
            font-size: 7em;
        }
    </style>
</head>

<body>
    <center>This is our home page.</center>
</body>
</html>

Now, we will render this page on a certain request by the user: 

JavaScript
app.get('/', (req, res) => {

    // The render method takes the name of the HTML
    // page to be rendered as input
    // This page should be in the views folder
    // in the root directory.
    res.render('home');

});

Now, the page home.ejs will be displayed on requesting localhost. To add dynamic content this render method takes a second parameter which is an object. This is done as: 

JavaScript
app.get('/', (req, res) => {

    // The render method takes the name of the HTML
    // page to be rendered as input.
    // This page should be in views folder in
    // the root directory.
    // We can pass multiple properties and values
    // as an object, here we are passing the only name
    res.render('home', { name: 'Akashdeep' });
});

const server = app.listen(4000, function () {
    console.log('listening to port 4000')
});

Now, We will embed the name to the HTML page as: 

html
<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
    <style type="text/css" media="screen">
        body {
            background-color: skyblue;
            text-decoration-color: white;
            font-size: 7em;
        }
    </style>
</head>

<body>
    <center>
        This is our home page.<br />
        Welcome <%=name%>, to our home page.
    </center>
</body>
</html>

It is used to embed dynamic content to the page and is used to embed normal JavaScript. Now embedding normal JavaScript: 

JavaScript
app.get('/', (req, res) => {

    // The render method takes the name of the html
    // page to be rendered as input.
    // This page should be in views folder 
    // in the root directory.
    let data = {
        name: 'Akashdeep',
        hobbies: ['playing football', 'playing chess', 'cycling']
    }

    res.render('home', { data: data });
});

const server = app.listen(4000, function () {
    console.log('listening to port 4000')
});

The final HTML content: 

HTML
<!-- Home.ejs -->

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
    <style type="text/css" media="screen">
        body {
            background-color: skyblue;
            text-decoration-color: white;
            font-size: 5em;
        }
    </style>
</head>

<body>
    Hobbies of <%=data.name%> are:<br />

        <ul>
            <% data.hobbies.forEach((item)=>{%>
                <li>
                    <%=item%>
                </li>
                <%});%>
        </ul>
</body>
</html>

Steps to run the program: After creating all the files go to the root directory of your project folder and run the below command

node index.js 

Type the node file_name.js command to run your program and see the output as displayed.

Output: 

Key Features of EJS

  • Embedded JavaScript: Allows you to embed JavaScript logic directly within your HTML.
  • Partial Templates: Supports partials, enabling you to reuse common template fragments (like headers and footers) across different pages.
  • Layout Support: EJS can be used with layout managers to create consistent layouts across multiple views.

Conclusion

EJS is a powerful and flexible templating engine that enhances your Node.js applications by allowing you to generate dynamic HTML content with ease. Its simplicity and integration with Express make it an ideal choice for developers looking to build server-rendered web applications quickly. Whether you’re developing a simple site or a complex web application, EJS provides the tools you need to create dynamic and interactive user interfaces.



Next Article

Similar Reads