Passing Data to EJS Templates
Last Updated :
22 May, 2024
EJS (Embedded JavaScript) is a simple templating language that lets you induce HTML language with plain JavaScript. It's especially popular in Node.js operations for rendering dynamic web runners. It is used to dynamically render HTML pages on the server side. This article will give a detailed companion on how to pass data to EJS templates.
Step to Create a NodeJS and Installing Module
Firstly, let's set up a basic Node.js project with EJS.
Step 1: Create a new directory for a project using the command:
mkdir ejs-DataPass
cd ejs-DataPass
Step 2: Initialize NPM using the command which will create a package.json file:
npm init -y
Step 3: Install the EJS module with Express dependency using the command:
npm i express ejs
Project Structure:
Project StructureThe updated dependencies in the package.json file will look like this.
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1"
}
Example: Below is an example to Passing Data to EJS Templates.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exapmle</title>
</head>
<body>
<h1>
Hello <%= name %>!
</h1>
</body>
</html>
JavaScript
import express from "express";
const app = express();
const port = 3000;
app.get("/", (req,res) =>{
res.render("index.ejs", {
name:"YourName"
});
});
app.listen(port, ()=>{
console.log(`Listening to port ${port}.`);
});
Output:
OutputPassing Data to the Template
In the app.js file, the res.render method is used to pass data to the EJS template. The second argument to res.render is an object containing key-value pairs. The keys correspond to the variable names in the EJS template, and the values are the data you want to pass.
In the example provided, the data object {name: "YourName"} is passed to the template. Within index.ejs, <%= name %> is placeholder that will be replaced with the actual value.
Dynamic Data Example
To demonstrate passing dynamic data, let's modify our example to include a list of items.
1. Update the route in index.js to include an array of items.
JavaScript
app.get("/", (req,res) =>{
res.render("index.ejs", {
name:"YourName",
items: items
});
});
2. Modify index.ejs to iterate over the items array and display each item.
Example: In this example, <% items.forEach(item => { %> and <% }) %> are EJS syntax for looping over the array and inserting each item's value into the HTML.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exapmle</title>
</head>
<body>
<h1>
Hello <%= name %>!
</h1>
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }) %>
</ul>
</body>
</html>
Output:
OutputUsing Partials
EJS supports partials, which are reusable snippets of code. To use partials, you typically create a partials directory inside views.
Create a Header Partial:
In views/partials/header.ejs, add some HTML content.
<header>
<h1>Welcome to GFG EJS data passsing example</h1>
</header>
Create a Footer Partial:
In views/partials/footer.ejs, add some HTML content.
<footer>
<p>Copyright © from footer</p>
</footer>
Include the Partial:
Modify index.ejs to include the partials.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Exapmle</title>
</head>
<body>
<%- include("partials/header.ejs") %>
<h1>
Hello <%= name %>!
</h1>
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }) %>
</ul>
<%- include("partials/footer.ejs") %>
</body>
</html>
The <%- include("partials/header") %> and <%- include("partials/footer.ejs") %> line includes the content of header.ejs and footer.ejs in the index.ejs template.
Output:
OutputHandling Form Data
EJS can also be used to render forms and handle form submissions. Here's a simple example:
Update index.js to Handle Form Submission:
Use body-parser to handle form data (body-parser is a Middleware).
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Form</title>
</head>
<body>
<form action="/submit" method="POST">
<input type="text"
name="username"
placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<% if (message) { %>
<p><%= message %></p>
<% } %>
</body>
</html>
JavaScript
import express from "express";
import bodyParser from "body-parser";
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.render("index.ejs", {
message:""
});
});
app.post("/submit", (req,res) =>{
const userName = req.body['username'];
res.render("index.ejs",{
message:`Hello from ${userName}!`
});
});
app.listen(port, ()=>{
console.log(`Listening to port ${port}.`);
});
Output:
OutputConclusion
EJS is a powerful yet simple templating language that integrates seamlessly with Node.js. By following this guide, you should be able to set up an EJS-powered application, pass dynamic data to your templates, use partials to organize your code, and handle form data efficiently. EJS allows for the creation of maintainable and dynamic web applications, making it a valuable tool in any web developer's toolkit.
Similar Reads
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
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
REST API Introduction REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read