Klement

Ejs Template Engine

2023-05-01 | Tag: Ejs

Learn how to use Ejs template engine and how to create a simple Ejs template.

Introduction

EJS (Embedded JavaScript) is a templating engine for Node.js applications. It allows you to embed JavaScript into your HTML to create dynamic and reusable templates, making it ideal for server-side rendering of web pages.

Why Use EJS?

Key Features of EJS:

- **Simple Syntax**: EJS uses plain JavaScript within templates.
- **Reusable Components**: Break your UI into reusable pieces with partials.
- **Logic in Templates**: Include JavaScript logic like loops and conditionals directly in your views.
- **Fast and Lightweight**: Minimal overhead compared to other templating engines.
- **Wide Adoption**: Easily integrates with Express and other Node.js frameworks.

Steps to Set Up EJS in Your Project:

mkdir ejs-example && cd ejs-example
npm init -y
npm install express ejs

Setting Up EJS with Express

Example: Configuring EJS in Express

const express = require('express');
const app = express();

// Set EJS as the view engine
app.set('view engine', 'ejs');

// Serve static files
app.use(express.static('public'));

// Define a route
app.get('/', (req, res) => {
  res.render('index', {
    title: 'Home Page',
    user: { name: 'John Doe', role: 'Admin' },
    items: ['Node.js', 'Express', 'EJS']
  });
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

EJS Template Syntax:

Basic EJS Syntax

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
  </head>
  <body>
    <h1>Welcome, <%= user.name %>!</h1>
    <p>Your role is: <%= user.role %>.</p>
    <ul>
      <% items.forEach(item => { %>
        <li><%= item %></li>
      <% }); %>
    </ul>
  </body>
</html>

EJS Advanced Features

1. Partials for Reusable Components

Example: Using Partials

// In a layout.ejs file:
<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
  </head>
  <body>
    <% include header %>
    <main>
      <%- body %>
    </main>
    <% include footer %>
  </body>
</html>

// In header.ejs:
<header><h1>My Website</h1></header>

// In footer.ejs:
<footer><p>&copy; 2025 My Website</p></footer>

2. Escaping and Unescaped Output

Escaping Output (Prevents XSS):

<%= userInput %> <!-- Escapes HTML to prevent XSS -->

Unescaped Output (Use with Caution):

<%- userInput %> <!-- Does not escape HTML -->

3. Conditional Rendering

Example: Conditional Logic in EJS

<% if (user.role === 'Admin') { %>
  <p>Welcome, Admin!</p>
<% } else { %>
  <p>Welcome, Guest!</p>
<% } %>

4. Looping Through Data

Example: Iterating Over an Array

<ul>
  <% items.forEach(item => { %>
    <li><%= item %></li>
  <% }); %>
</ul>

EJS with Middleware for Error Handling

Example: Handling Errors with EJS

// Middleware for 404 errors
app.use((req, res, next) => {
  res.status(404).render('404', { title: 'Page Not Found' });
});

// Middleware for server errors
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).render('500', { title: 'Server Error' });
});
EJS is an excellent choice for server-side rendering in Node.js applications, offering simplicity, flexibility, and robust features.