Passing Dynamic Variables to EJS Templates


In EJS (Embedded JavaScript), you can create dynamic web pages by inserting variables into your HTML templates. This allows you to generate content dynamically based on data passed from the server. Here’s a guide on how to use variables in EJS templates to render dynamic content.

1. Passing Variables to EJS Templates

To render dynamic content in EJS, you first need to pass variables from your Express route handler to the EJS template.

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'); // Define a route that renders an EJS template with dynamic content app.get('/greeting', (req, res) => { const user = { name: 'Alice', age: 30 }; res.render('greeting', { user }); }); // Start the server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });

In this example:

  • We define a route /greeting that renders an EJS template called greeting.ejs.
  • We pass a user object with properties name and age to the template.

2. Accessing Variables in EJS Templates

In your EJS template, you can access the variables passed from the server using special EJS syntax.

Example Template (views/greeting.ejs):

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Greeting Page</title> </head> <body> <h1>Hello, <%= user.name %>!</h1> <p>You are <%= user.age %> years old.</p> </body> </html>

In this template:

  • <%= user.name %> outputs the name property of the user object.
  • <%= user.age %> outputs the age property of the user object.

3. Using Variables for Conditional Content

You can use variables to control the display of content based on conditions.

Example Template with Conditional Content:

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>

In this example:

  • The <% if (status.loggedIn) { %> block checks if the user is logged in and displays a welcome message if true, or a prompt to log in if false.

4. Using Variables in Loops

You can loop through arrays or objects and render lists or tables dynamically.

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(function(item) { %> <li><%= item %></li> <% }); %> </ul> </body> </html>

In this example:

  • The <% items.forEach(function(item) { %> loop iterates through the items array and renders each item as a list item.

5. Escaping and Raw HTML

By default, EJS escapes HTML content to prevent XSS attacks. However, you can use <%- %> to render unescaped HTML if needed.

Example with Raw HTML:

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 Variables: Use res.render() to pass variables from your Express routes to EJS templates.
  • Accessing Variables: Use <%= %> to output variables in your templates.
  • Conditional Content: Use <% if %> and <% else %> for conditional rendering.
  • Loops: Use <% forEach %> to iterate over arrays or objects.
  • Escaping HTML: Use <%- %> for rendering raw HTML if needed.

By leveraging these techniques, you can create dynamic, data-driven web pages with EJS and Express.