How to use Ejs in JavaScript ?
Last Updated :
08 Jan, 2025
EJS or Embedded Javascript Templating is a templating engine used by Node.js. The template engine helps to create an HTML template with minimal code. Also, it can inject data into the HTML template on the client side and produce the final HTML.
Installation Steps
Install the module using the following command:
npm install ejs --save
Note:
In the commands above, "npm" stands for the Node Package Manager, which is where all the dependencies are stored. The
"--save" flag is no longer needed after Node 5.0.0, as all the modules we install will now be added to dependencies automatically.
To start, we need to set EJS as our templating engine with Express. Express is a Node.js web application server framework designed for building single-page, multi-page, and hybrid web applications. It has become the standard server framework for Node.js.
Data passed from the server is sent to the EJS file and then we can access that data using the below line and it will give that data to h, p, or another text tag.
<%= data %>
If we want to use this data for normal js operations like if-else and loops or other programming statements we can write it in the following form:
<% if(data == "1"){%>
<h5>Cricket</h5>
<%}else{%>
<h5>Football</h5>
<%}%>
Now to access that data in the script tag of the EJS file or the .js file all you need to do is to pass that data in another variable as below:
let data = '<%-data%>'
Now you can perform any operation on the data variable that has the same value as the EJS passed data variable.
Example: Implementation to use EJS in our project.
javascript
// Filename - index.js
// Set express as Node.js web application
// server framework.
// Install it using 'npm install express' command
// and require like this:
let express = require('express');
let app = express();
// Set EJS as templating engine
app.set('view engine', 'ejs');
app.get("/", function(req, res) {
res.render("home", {name:'Chris Martin'});
});
// Server setup
app.listen(3000, function(req, res) {
console.log("Connected on port:3000");
});
The default behaviour 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 request in our node project.
HTML
<!-- home.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
</head>
<body>
<!-- Text from EJS variable
passed from server -->
<h2>
Text from EJS variable passed
from server is =
</h2>
<h2 style="color:red">
<%=name%>
</h2>
<br>
<!-- Text from EJS variable
passed from script tag -->
<h2 style="color: blue;">
Text from EJS variable passed
from script tag =
</h2>
<h2 style="color: blue;" id="text_from_script">
</h2>
<br>
<!-- Text from EJS variable passed
from script tag after manipulation -->
<h2 style="color: green;">
Text from EJS variable passed from
script tag after manipulation =
</h2>
<h2 style="color: green;"
id="text_from_script_manipulated">
</h2>
<script>
let name = '<%-name%>'
let heading = document
.getElementById('text_from_script');
heading.innerText = name;
name = "Mr. " + name;
let heading_man = document.getElementById(
'text_from_script_manipulated');
heading_man.innerText = name;
</script>
</body>
</html>
The "name" variable has been passed from the server to the 'name.ejs' file and displayed using an h2 tag. To use the "name" variable in the script tag, all we did was declare a variable and assign the EJS variable to the declared variable using:
let name = '<%-name%>'
Step to Run Application: Run the application using the following command from the root directory of the project
node index.js
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read