Handling dynamic content in EJS
Handling dynamic content in EJS (Embedded JavaScript) involves using EJS syntax to embed JavaScript expressions, variables, and logic within your HTML templates. This allows you to create web pages that adapt based on the data passed from your server. Here's a comprehensive guide on how to manage dynamic content in EJS templates.
1. Passing Data to EJS Templates
Dynamic content is driven by data passed from your Express route handlers to EJS templates. This data can be variables, objects, arrays, or any other JavaScript data type.
Example:
Server-Side Code (Express):
const express = require('express');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
app.set('views', 'views');
// Route that renders a template with dynamic data
app.get('/profile', (req, res) => {
const user = {
name: 'Alice',
age: 30,
hobbies: ['Reading', 'Hiking', 'Cooking']
};
res.render('profile', { user });
});
// Start the server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
EJS Template (views/profile.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= user.name %>'s Profile</title>
</head>
<body>
<h1>Profile of <%= user.name %></h1>
<p>Age: <%= user.age %></p>
<h2>Hobbies:</h2>
<ul>
<% user.hobbies.forEach(hobby => { %>
<li><%= hobby %></li>
<% }); %>
</ul>
</body>
</html>
2. Outputting Data
Use EJS syntax to embed variables and expressions directly into your HTML. There are several ways to output data:
<%= %>: Output the value of an expression, escaping HTML to prevent XSS attacks.
<p>Name: <%= user.name %></p>
<%- %>: Output raw HTML without escaping.
<%- user.bio %> <!-- Use with caution to avoid XSS -->
3. Conditional Rendering
You can use conditional statements to display content based on conditions.
Example:
Server-Side Code:
app.get('/status', (req, res) => {
const status = {
loggedIn: true,
username: 'Alice'
};
res.render('status', { status });
});
EJS Template (views/status.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Status Page</title>
</head>
<body>
<% if (status.loggedIn) { %>
<h1>Welcome back, <%= status.username %>!</h1>
<% } else { %>
<h1>Please log in.</h1>
<% } %>
</body>
</html>
4. Looping Through Data
You can loop through arrays or objects to dynamically generate content.
Example:
Server-Side Code:
app.get('/items', (req, res) => {
const items = ['Apple', 'Banana', 'Cherry'];
res.render('items', { items });
});
EJS Template (views/items.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Items List</title>
</head>
<body>
<h1>Items List</h1>
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }); %>
</ul>
</body>
</html>
5. Using Partials and Layouts
To maintain a consistent layout across pages, you can use partials (reusable pieces of HTML) and layouts. EJS doesn’t support layouts out of the box, but you can use express-ejs-layouts
to handle layouts.
Install Express EJS Layouts:
npm install express-ejs-layouts
Configure Layouts:
app.js
:
const expressEjsLayouts = require('express-ejs-layouts');
app.use(expressEjsLayouts);
app.set('layout', 'layout'); // Default layout file
Layout Template (views/layout.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
</head>
<body>
<%- body %> <!-- Render content from the view here -->
</body>
</html>
View Template (views/index.ejs
):
<h1>Welcome to the Home Page</h1>
<p>This is some content.</p>
6. Escaping HTML
By default, EJS escapes HTML to prevent XSS attacks. Use <%- %>
to render raw HTML if necessary, but be cautious with user-generated content.
Example:
Server-Side Code:
app.get('/html', (req, res) => {
const htmlContent = '<strong>This is bold text</strong>';
res.render('html', { htmlContent });
});
EJS Template (views/html.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Raw HTML Example</title>
</head>
<body>
<h1>Raw HTML Content:</h1>
<%- htmlContent %> <!-- Renders HTML directly -->
</body>
</html>
Summary
- Passing Data: Use
res.render()
in Express to pass data to EJS templates. - Outputting Data: Use
<%= %>
to render escaped content, and<%- %>
for raw HTML. - Conditional Rendering: Use
<% if %>
and<% else %>
for displaying content based on conditions. - Looping: Use loops like
<% forEach %>
to iterate through arrays or objects. - Partials and Layouts: Use partials for reusable HTML, and
express-ejs-layouts
for layout management. - Escaping HTML: Be cautious with
<%- %>
and ensure you sanitize user-generated content to prevent XSS.
Handling dynamic content in EJS allows you to build interactive and data-driven web applications by embedding server-side logic and data into your HTML templates.