Express JS passing data to EJS templates
Passing data to templates in an Express.js application using EJS (Embedded JavaScript) is a straightforward process. Here’s a step-by-step explanation:
1. Setting Up EJS in Express.js
First, you need to set up EJS as the templating engine in your Express application. Here’s how you do it:
Install EJS:
Run the following command to install EJS via npm:
npm install ejs
Configure Express to Use EJS:
In your Express application file (typically
app.js
orserver.js
), configure the view engine to use EJS:const express = require('express'); const app = express(); // Set the view engine to EJS app.set('view engine', 'ejs'); // Optionally, set the views directory if it's not in the default location app.set('views', path.join(__dirname, 'views'));
2. Creating EJS Templates
Create EJS template files in the views
directory. For example, you might create a file called index.ejs
:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= message %></h1>
<ul>
<% items.forEach(function(item) { %>
<li><%= item %></li>
<% }); %>
</ul>
</body>
</html>
3. Passing Data to Templates
To pass data to your EJS templates, you do this in your route handlers. Here’s an example of how to do this:
Define a Route:
In your Express application, define a route where you render the EJS template and pass data to it:
app.get('/', (req, res) => { const data = { title: 'My Page Title', message: 'Hello, World!', items: ['Item 1', 'Item 2', 'Item 3'] }; res.render('index', data); });
In this example,
res.render('index', data)
tells Express to render theindex.ejs
template and pass thedata
object to it.
4. Accessing Data in EJS Templates
Within your EJS template (index.ejs
), you access the data using EJS syntax. The variables you pass in the data
object are available directly in the template:
<%= title %>
outputs thetitle
value.<%= message %>
outputs themessage
value.<% items.forEach(function(item) { %>
iterates over theitems
array.
5. Running Your Application
Start your Express server, and navigate to the route you defined to see your EJS template rendered with the data you passed:
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
By following these steps, you can efficiently pass data to EJS templates in an Express.js application and dynamically render content based on that data.