Passing 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.
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.
<!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:
Passing Data to EJS Templates
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.