Template engine is a part of Express that enables us to use static files in our applications.Template engine converts variables to values and changes the template to HTML files to send to the client.
The default template engine of Express is Jade, but EJS is the most commonly used engine. In this article we will be discussing EJS only.
In this article we will cover
Setting up a project
Configuring server.js to use EJS
Creating EJS partials
Using partials in views
Passing data to EJS files (views and partials).
If you don’t have nodeJS installed see How to install and configure nodeJS.
Open up the terminal and create the project directory.
mkdir ejs-starter
Then, navigate to the directory.
cd ejs-starter
Now, initialize npm in it.
npm init -y
Let’s install the npm modules we will need to build the application.
npm i -S express ejs
Let’s install another module that will rerun our application automatically every time we make changes to it.
npm i nodemon --save-dev
When we have all the required modules, create a server.js file and configure it to use EJS.
Also, set routes for the index page and magic page.
Create a server.js file, open your editor, and write down the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const express = require("express"),
app = express();
//setting view engine to ejs
app.set("view engine", "ejs");
//route for index page
app.get("/", function (req, res) {
res.render("index");
});
//route for magic page
app.get("/magic", function (req, res) {
res.render("magic");
});
app.listen(8080, function () {
console.log("Server is running on port 8080 ");
});
Let’s understand what this code does.
We are importing the Express module and declaring its instance as an app.
We are setting up a server to listen at port 8080 by using app.listen().
We are telling our server to use EJS template engine in line,
app.set(“view engine”, “ejs”).
We also set up routes / and /magic to render index and magic EJS pages respectively.
You can notice that our server shows user HTML content by using res.render(). Note that this res.render method will look for EJS files in the views directory so we only have to give the file name overall path will be interpreted as /views/index .
Start the server by running the following command in the terminal.
nodemon server.js
Now we will create view using EJS.
Before we start implementing partials, let’s understand what partials are. Partials are code blocks that are reused many times in an application. For example, in this tutorial we are going to create two view pages, index and magic, and in both of these files we will need to write a header and footer. We can create a separate one for each and reuse it in both view pages. Let’s create the files header.ejs and footer.ejs now.
Create views directory.
mkdir views
Create a subdirectory named partials under views.
mkdir view/partials
Now create header.ejs in partials directory, open that file in your editor, and write down the following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Title</title>
<!-- CSS link (loading Semantic UI from a CDN) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" integrity="sha512-8bHTC73gkZ7rZ7vpqUQThUDhqcNFyYi2xgDgPDHc+GXVGHXq+xPjynxIopALmOPqzo9JZj0k6OqqewdGO3EsrQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
body { padding:50px; }
</style>
</head>
<body class="container">
<header>
<div class="ui inverted menu">
<a class="item" href="/">
Home
</a>
<a class="item" href="/magic">
Magic
</a>
</div>
</header>
This EJS code is similar to HTML, there are no EJS variables. It is simple HTML containing a header component which also loads CDN to semantic UI (a CSS library). Then, in the body section we have navbar created using Simatic UI classes in HTML under <header>
tags.
Now let’s create the footer.
Create the footer.js file inside partials and write down the given code.
1 2 3 4 5
<div class="ui inverted footer"> <div class="ui container"> Topcoder 2021. All Rights Reserved </div> </div>
Now we will use these partials in our view files index and magic.
We have two partials defined. We will use them in index.ejs view page.
We can include any partial by writing the following syntax where we want to import a partial.
Note: we have replaced all occurances of %
with due to syntax highlighter issues.
<%- include('RELATIVE/PATH/TO/FILE') %>
Now create an index.ejs file in views directory and write down the given code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<%- include('../partials/header'); %> <main> <div class="ui segment"> <h1>At least we can see something now</h1> <p>This is visual of templating through EJS</p> </div> </main> < footer > <%- include('../partials/footer'); %> </footer> < /body> < /html>
Save file, open browser, and enter url localhost:8080. You should see this web page.
Now create magic.ejs and write down the code as given.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<%- include('./partials/header'); %> <main> <div class="ui grid segment "> <div class="segment eight wide column"> <h1>At least we can see something now</h1> <p>This is visual of templating through EJS</p> </div> <div class="segment eight wide column"> <h1> Look I just Magically appeared here!</h1> </div> </div> </main> < footer > <%- include('./partials/footer'); %> </footer> < /body> < /html>
And now visit localhost:8080/magic in the browser.
Now let’s see how we can pass data to view pages.
Let’s set up some variables and lists to pass to index.js.
Open server.js and modify the index route as given.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const express = require("express"),
app = express();
//setting view engine to ejs
app.set("view engine", "ejs");
//route for index page
app.get("/", function (req, res) {
var characters = [
{
name: 'Harry',
designation: "Student"
},
{
name: 'Dumbledore',
designation: "Headmaster"
},
{
name: 'Snape',
designation: "Professor"
},
{
name: 'Hermione',
designation: "Student"
}
];
var subheading = "I though we should involve some magic";
res.render("index", {
characters: characters,
subheading: subheading
});
});
//route for magic page
app.get("/magic", function (req, res) {
res.render("magic");
});
app.listen(8080, function () {
console.log("Server is running on port 8080 ");
});
Let’s use the variables we just defined in index.ejs.
Display a single variable in EJS:
A single variable can be represented by using syntax <%= variable_name %>.
We can use subheading in index.ejs that we passed as given.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%- include('./partials/header'); %>
<main>
<div class="ui segment">
<h1>At least we can see something now</h1>
<p>This is visual of templating through EJS</p>
</div>
<h2>Variable</h2>
<p><%= subheading %></p>
</main>
<
footer >
<%- include('./partials/footer'); %>
</footer>
<
/body> <
/html>
And now you should see the webpage in your browser as:
Now we know how to render a single variable. Let’s see how we can loop over a list to display each element of the list.
We can iterate over an array using .forEach function of Javascript.
Open index.js and modify it as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<%- include('./partials/header'); %>
<main>
<div class="ui segment">
<h1>At least we can see something now</h1>
<p>This is visual of templating through EJS</p>
<h2>Variable</h2>
<p><%= subheading %></p>
<ul>
<% characters.forEach(function(character) { %>
<li class="ui segment">
<strong><%= character.name %></strong>
is <%= character.designation %> at hogwarts.
</li>
<% }); %>
</ul>
</div>
</main>
<
footer >
<%- include('./partials/footer'); %>
</footer>
<
/body> <
/html>
You can notice that for each character in the characters array we passed we are displaying a list point with name and designation associated with each. If you open the browser, the webpage will now look like:
In this article you learned how to render templates using EJS and how to pass variables between files. Hence, EJS helps to develop simple applications very easily.