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
How JavaScript Works? JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f
13 min read
How to Access EJS Variable in Javascript Logic ? EJS stands for Embedded JavaScript. It is a templating language used to generate dynamic HTML pages with data from the server by embedding JavaScript code. Features of EJSDynamic Content: Based on data from servers or other sources, we can generate a dynamic HTML template.Partial Templates: Partials
3 min read
Uses of JavaScript JavaScript is a versatile programming language extensively used in web development. It empowers interactive features like form validation, dynamic content updates, and user interface enhancements. Furthermore, it's employed in server-side scripting, mobile app development, game development, and even
3 min read
How to Run JavaScript in Visual Studio? To run JavaScript in Visual Studio, you can either use Node.js in the Terminal or the Code Runner extension. Both methods allow you to execute JavaScript code easily and efficiently within the Visual Studio environment.Using Node.js in TerminalNode.js is a JavaScript runtime that allows you to execu
2 min read
How to Execute JavaScript Code ? Javascript is a high-level, Just In Time compiled programming language which converts the entire machine code at once and then executes it immediately. Javascript code is executed by the Javascript Engine, which is separate software. Different browsers have their own implementation of JS Engine embe
2 min read
How to Pass variables to JavaScript in Express JS ? Express is a lightweight framework that sits on top of Node.jsâs web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. When working with Express.js you may encounter scenarios where you
2 min read
ESLint - Pluggable JavaScript linter Before getting into ESlint first you should be aware of linting. It is the process of checking the code for any errors. A Linter is an automated tool that runs on a static piece of code to find any kind of discrepancy arising due to formatting or due to bad coding practices. Running a Linting tool o
3 min read
Introduction to JavaScript JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at
7 min read
How to Install & Use EJS Template Engine ? EJS (Embedded JavaScript) is mainly a templating language for JS which allows dynamic content generation in web-based applications. This EJS Template allows us to embed the JS code directly in the HTML markup, which enables the integration of data and logic into the presentation layer. We can use EJ
3 min read
How to use Template Engines in Express JS ? Express.js is a popular web framework for Node.js that simplifies the process of building web applications. One of the key features of Express is its ability to integrate with template engines, allowing developers to dynamically generate HTML pages with data from their server. In this article, we'll
3 min read