Introduction:

When fast for creating a node application, the faster way for template the application is very necessary and important sometimes.

Jade is the default template engine for Express, but Jade syntax is very complex for many use cases for Express JS web applications.

Embedded JavaScript (EJS) can be an alternative template engine for the Express JS template requirement and usages.

Prerequisites:

For using EJS template in your application, we require:

Step 1: Setting Up Project:

First, open terminal window or command prompt(cmd) and create a new Project directory.

$ mkdir ejs-project

Then navigate to the newly created directory.

$ cd ejs-project

At this following point, we can initialize a new NPM project.

$ npm init -y

Next, you must install the express package.

$ npm install express

Then install EJS package.

$ npm install ejs

And then, we have a new project ready to use EJS and Express.

Configuration with server.js

With all dependencies installed in project, let’s configure the application for using EJS and set up routes for Index Page and the About Page.

Create the new server.js file and open with code editor and add following lines of code:

var express=require('express');
var app=express();
//set view engine to ejs
app.set=("view engine","ejs");
//index page
app.get('/',function(req,res){
res.render('pages/index');
});
//about page
app.get('/about',function(req,res){
res.render('pages/about');
});
app.listen(8080);
console.log('Server is listening on port 8080');

The code defines application and it listens on port 8080.

The below code also set EJS as a view engine for the express applications which we are using using:

`app.set('view engine', 'ejs');`

Notice how code sends view to the user by using res.render(). It’s very important to note that res.render() will look into  views folder for the views. So you only have to define  the pages/index since its full path is views/pages/index.

Step-2 – Creating the EJS Partials

Like lot of the applications you build, there will be lot of code which will be reused. These are considered as partials. In the given example, there are three partials which will be reused in the Index page and About page: head.ejsheadervalue.ejs, and footervalue.ejs. Let us make those files now.

Create a new views directory:

$ mkdir views

Then, create a new partials subdirectory:

$ mkdir views/partials

In this current directory, we will create a new head.ejs file and open in the code editor. Add following lines of code:

<meta charset="UTF-8">
<title>EJS Is Fun</title>

<!-- CSS (load bootstrap from a CDN) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">
<style>
  body { padding-top:50px; }
</style>

This code contains metadata the head for an HTML document. It also includes Bootstrap styles.

Next, create a new headervalue.ejs file and open it in the code editor. Add the following lines of code:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="/">EJS Is Fun</a>
  <ul class="navbar-nav mr-auto">
    <li class="nav-item">
      <a class="nav-link" href="/">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="/about">About</a>
    </li>
  </ul>
</nav>

This code contains the navigation for the HTML document which uses several classes from Bootstrap for styling.

Next, create a new footervalue.ejs file and open with code editor and add the following lines of code:

<p class="text-center text-muted">&copy; Copyright 2020 The Awesome People</p>

The above code contains copyright information and use several classes from Bootstrap for styling of the data.

Next, we will use the above written partials in index..ejs and about.ejs.

Step 3 — Adding the EJS Partials to Views

Now, we have three partials defined, which we can include it in views.

Use <%- include('RELATIVE/PATH/TO/FILE) %> to embed EJS partial into another file.

Then, create new pages subdirectory:

$ mkdir views/pages

In the using directory, create a new index.ejs file and open it into code editor. Add following lines of code:

<!DOCTYPE html>
<html lang="en">
<head>
  <%- include('../partials/head'); %>
</head>
<body class="container">

<header>
  <%- include('../partials/header'); %>
</header>

<main>
  <div class="jumbotron">
    <h1>This is great</h1>
    <p>Welcome to templating using EJS</p>
  </div>
</main>

<footer>
  <%- include('../partials/footer'); %>
</footer>

</body>
</html>

Save changes to the file and then run the application:

$ node server.js

Next, create a new about.ejs file and open with the code editor. Add following lines of code:

<!DOCTYPE html>
<html lang="en">
<head>
  <%- include('../partials/head'); %>
</head>
<body class="container">

<header>
  <%- include('../partials/header'); %>
</header>

<main>
<div class="row">
  <div class="col-sm-8">
    <div class="jumbotron">
      <h1>This is great</h1>
      <p>Welcome to templating using EJS</p>
    </div>
  </div>

  <div class="col-sm-4">
    <div class="well">
      <h3>Look I'm A Sidebar!</h3>
    </div>
  </div>
</div>
</main>

<footer>
  <%- include('../partials/footer'); %>
</footer>

</body>
</html>

This code adds Bootstrap sidebar to show that how partials can be erected to reuse across the different templates and pages.

Save changes into file and then run the application:

$ node server.js

If you visit http://localhost:8080/about in a web browser, we will observe the About page with a sidebar:

Now we can start using EJS for passing data from the Node application to the views.

Step 4 — Passing Data to Views and Partials

Let us define some fundamental variables and list to pass to Index page.

Revisit the server.js in your code editor and add the following lines of code inside the app.get('/') route:

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

// set the view engine to ejs
app.set('view engine', 'ejs');

// use res.render to load up an ejs view file

// index page
app.get('/', function(req, res) {
  var mascots = [
    {name:'Sammy', organization:"Nanostuffs", birth_year:2010},
    {name:'Adam', organization:"Linux", birth_year:2015},
   {name:'XYZ', organization:"Windows", birth_year:2017},
  ];
 var tagline="Hello Omkar";

  res.render('pages/index' , {
    mascots:mascots,
    tagline:tagline

  });
});

// about page
app.get('/about', function(req, res) {
  res.render('pages/about');
});

app.listen(8080);
console.log('Server is listening on port 8080');

This code defines an array which is called mascots and a string which is called tagline. Next, let us use them into index.ejs.

Rendering a Single Variable in EJS

For echoing single variable, you can use <%= tagline %>.

Revisit index.ejs in code editor and add the following lines of code:

<!DOCTYPE html>
<html lang="en">
<head>
  <%- include('../partials/head'); %>
</head>
<body class="container">

<header>
  <%- include('../partials/header'); %>
</header>

<main>
  <div class="jumbotron">
    <h1>This is great</h1>
    <p>Welcome to templating using EJS</p>

    <h2>Variable</h2>
    <p><%= tagline %></p>
  </div>
</main>

<footer>
  <%- include('../partials/footer'); %>
</footer>

</body>
</html>

This code will show the tagline value on the Index page.

Looping Over Data in EJS

To loop over data, you can use .forEach.

Revisit index.ejs in code editor and add the following lines of code:

<!DOCTYPE html>
<html lang="en">
<head>
  <%- include('../partials/head'); %>
</head>
<body class="container">

<header>
  <%- include('../partials/header'); %>
</header>

<main>
  <div class="jumbotron">
    <h1>This is great</h1>
    <p>Welcome to templating using EJS</p>

    <h2>Variable</h2>
    <p><%= tagline %></p>

    <ul>
      <% mascots.forEach(function(mascot) { %>
        <li>
          <strong><%= mascot.name %></strong>
          representing <%= mascot.organization %>,
          born <%= mascot.birth_year %>
        </li>
      <% }); %>
    </ul>
  </div>
</main>

<footer>
  <%- include('../partials/footer'); %>
</footer>

</body>
</html>

Save the changes into this file and then run the application:

$ node server.js

If you visit http://localhost:8080/ in a web browser, you can observe the Index page with the mascots:

Conclusion

In this article, we have learned how to use EJS into Express application, including repeatable parts of site, and passing data to the views.

EJS helps and guides you to build apps when we do not require additional complexity. By using partials and having the ability to easily pass variables to the views, we can build some great web applications quickly.

Refer the EJS documentation for additional information on features and syntax.