Using the EJS template in the node.js application
Hello. In this tutorial, we will understand and see a practical implementation of ejs template in the nodejs and express js application.
1. Introduction
ejs or Embedded Javascript Templating is a template engine used by nodejs applications. The template engine helps to work on the html code with minimal code. Ejs is one of the most common templating engines used these days that offer important features like –
- Control flow with
<% %>
tag - Escaped output with
<%= %>
tag - Unescaped raw output with
<%- %>
tag - Newline-trim mode with
-%>
ending tag - Etc
Ejs provides several tags such as –
<%
= Scriptlet tag, for control flow, no output<%_
= Whitespace Slurping Scriptlet tag, strips all whitespace before it<%=
= Outputs the value into the template (escaped)<%-
= Outputs the unescaped value into the template<%#
= Comment tag, no execution, no output<%%
= Outputs a literal <%%%>
= Outputs a literal %>%>
= Plain ending tag-%>
= Trim-mode (newline slurp) tag, trims the following newline_%>
= Whitespace Slurping ending tag, removes all whitespace after it
Refer to the documentation here for a complete list. The below code snippet shows a basic example of it –
Code snippet
<% if (student) { %> <p><%= student.name %></p> <% } %>
1.1 Setting up Node.js
To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.
2. Using the EJS template in the nodejs application
To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE. Let a take a quick peek at the project structure –
2.1 Setting up dependencies
Navigate to the project directory and run npm init -y
to create a package.json
file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Replace the generated file with the code given below –
package.json
{ "name": "ejs", "version": "1.0.0", "description": "Understanding ejs in nodejs application", "main": "index.js", "scripts": { "dev": "nodemon index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "ejs", "nodemon", "nodejs", "expressjs", "jcg", "practice" ], "author": "geek", "license": "MIT", "dependencies": { "ejs": "^3.1.7", "express": "^4.17.3" }, "devDependencies": { "nodemon": "^2.0.15" } }
Once the file is replaced trigger the below npm
command in the terminal window to download the different packages required for this tutorial.
Downloading dependencies
npm install
2.2 Setting up the template page
Create a file inside the views
responsible to show the students’ information received from the backend endpoint.
views/students.ejs
<!DOCTYPE html> <html lang="en"> <head> <title>Ejs</title> </head> <body> <h1><%= title %></h1> <% if (students && students.length > 0) { %> <ul> <% students.forEach((item, index) => { %> <li>#<%= (index + 1) %></li> <li>Name: <%= item.name %></li> <li>Email: <%= item.email %></li> <% if (item.hobbies && item.hobbies.length > 0) { %> <li> Hobbies are: <ul> <% item.hobbies.forEach((hobby) => { %> <li><%= hobby %></li> <% }) %> </ul> </li> <% } else { %> <li>No hobbies found.</li> <% } %> <br /> <br /> <% }) %> </ul> <% } else { %> <p>No students found.</p> <% } %> </body> </html>
2.3 Setting up the implementation file
Create a file responsible to describe the implementation. The file will be responsible to expose an endpoint that will return the result to the ejs template (students.ejs
). For simplicity, the endpoint will be sending the mock student’s data but in real work applications, the data will be fetched from the database.
index.js
const express = require("express"); let app = express(); app.set("view engine", "ejs"); // http get endpoint - http://localhost:3005/ // shows the result on the students.ejs page app.get("/", (req, res) => { const data = [ { name: "John doe", email: "john.doe@test.com", hobbies: ["Cricket", "Football", "Swimming"] }, { name: "Adam doe", email: "adam.joe@test.com", hobbies: ["Football", "Table Tennis", "Tennis", "Badminton"] }, { name: "Oliver james", email: "oliver.james@test.com", hobbies: [] }, { name: "Michael jacob", email: "michael.jacob@test.com", hobbies: ["Tennis"] } ]; res.render("students", { title: "Student Information", students: data }); }); // driver code const port = 3005; app.listen(port, () => { console.log(`Service endpoint = http://localhost:${port}`); });
3. Run the Application
To run the application navigate to the project directory and enter the following command as shown below in the terminal.
Run command
$ npm run dev
If everything goes well the application will be started successfully at the service endpoint – http://localhost:3005
4. Demo
The application exposes a single endpoint (http://localhost:3005/
). Once the endpoint is hit in the browser the below output will be shown illustrating the ejs template implementation.
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
5. Summary
In this tutorial, we saw the implementation of ejs template in an express js application. You can download the source code from the Downloads section.
6. Download the Project
This was a tutorial to implement ejs template in a nodejs and express js application.
You can download the full source code of this example here: Using the EJS template in the nodejs application