Setting up and rendering templates with Express.js and EJS


Setting up and rendering templates with Express.js and EJS involves configuring Express to use EJS as the templating engine and creating EJS templates that dynamically generate HTML content. Here’s a step-by-step guide to help you understand the process:

1. Set Up Your Project

Start by creating a new Node.js project and installing Express and EJS.

mkdir my-express-app cd my-express-app npm init -y npm install express ejs

2. Create the Basic Express Application

Create a file named app.js (or index.js) for your Express application.

app.js:

const express = require('express'); const app = express(); const path = require('path'); // Set EJS as the view engine app.set('view engine', 'ejs'); // Set the directory where the views (EJS templates) are located app.set('views', path.join(__dirname, 'views')); // Define a route app.get('/', (req, res) => { // Render the EJS template and pass data to it res.render('index', { title: 'Home Page', message: 'Welcome to EJS with Express!' }); }); // Start the server app.listen(3000, () => { console.log('Server is running on port 3000'); });

In this setup:

  • app.set('view engine', 'ejs') tells Express to use EJS as the templating engine.
  • app.set('views', path.join(__dirname, 'views')) specifies the directory where your EJS templates will be stored.

3. Create EJS Templates

Create a directory named views in your project root. This is where you will place your EJS template files.

Inside the views directory, create an index.ejs file.

views/index.ejs:

<!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= message %></h1> <p>This is a simple example of using EJS with Express.js.</p> </body> </html>

In this template:

  • <%= title %> and <%= message %> are placeholders that will be replaced with data passed from the route handler.

4. Rendering EJS Templates

In the route handler (in app.js), use res.render() to render the EJS template. Pass an object containing the data you want to display in the template.

app.get('/', (req, res) => {

app.get('/', (req, res) => { // Render 'index.ejs' and pass data to it res.render('index', { title: 'Home Page', message: 'Welcome to EJS with Express!' }); });

This code tells Express to:

  • Render the index.ejs template located in the views directory.
  • Pass an object with title and message properties to the template.

5. Run Your Application

Start your Express server using Node.js:

node app.js

Visit http://localhost:3000 in your browser. You should see the rendered HTML page with the title and message set dynamically by the EJS template.

6. Advanced Usage

Passing Dynamic Data

You can pass more complex data structures (arrays, objects) to your EJS templates.

Example Route with Dynamic Data:

app.get('/users', (req, res) => { const users = [ { name: 'Alice', age: 28 }, { name: 'Bob', age: 24 }, { name: 'Charlie', age: 30 } ]; res.render('users', { users }); });

views/users.ejs:

<!DOCTYPE html> <html> <head> <title>User List</title> </head> <body> <h1>User List</h1> <ul> <% users.forEach(user => { %> <li><%= user.name %> - <%= user.age %> years old</li> <% }) %> </ul> </body> </html>

Using Partials and Layouts

To avoid code duplication, you can use partials (reusable templates) and layouts.

views/partials/header.ejs:

<header> <h1>My Website</h1> </header>

views/index.ejs:

<!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <%- include('partials/header') %> <h2><%= message %></h2> <p>This is a simple example of using EJS with Express.js.</p> </body> </html>

In this example, header.ejs is included in index.ejs using <%- include('partials/header') %>.

Summary

  1. Set Up EJS: Install and configure EJS as the view engine in your Express application.
  2. Create EJS Templates: Place your EJS template files in the views directory.
  3. Render Templates: Use res.render() to generate HTML from your EJS templates, passing data as needed.
  4. Use Advanced Features: Handle dynamic data, create partials, and manage layouts to build more complex applications.

EJS provides a flexible way to generate dynamic HTML in your Express applications, allowing you to embed JavaScript logic directly within your HTML templates.