EJS Templating Engine

5.0.2 · active · verified Sun Apr 19

EJS (Embedded JavaScript) is a popular, fast, and lightweight templating engine for Node.js and browsers. It enables the rendering of dynamic HTML by embedding plain JavaScript directly within template files using special tags like `<% %>` for control flow, `<%= %>` for escaped output, and `<%- %>` for unescaped raw output. The current stable version is 5.0.2, with an active release cadence. Key differentiators include its straightforward approach, leveraging native JavaScript for logic, and broad compatibility across Node.js environments (CommonJS and ES Modules) and all modern browsers, down to very old ones. It offers features such as static caching of compiled functions and templates, custom delimiters, and full compliance with the Express view system, making it a common choice for server-side rendering in web applications due to its simplicity and effectiveness.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up EJS with an Express application to render templates from files and also shows how to render EJS template strings directly using `ejs.render`.

import ejs from 'ejs';
import express from 'express';
import path from 'path';

const app = express();
const port = process.env.PORT ?? 3000;

// Configure EJS as the view engine for Express
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Create a simple EJS template file (e.g., views/index.ejs):
// <!-- views/index.ejs -->
// <!DOCTYPE html>
// <html lang="en">
// <head>
//     <meta charset="UTF-8">
//     <meta name="viewport" content="width=device-width, initial-scale=1.0">
//     <title>EJS Example</title>
// </head>
// <body>
//     <h1>Hello, <%= user.name %>!</h1>
//     <% if (isAdmin) { %>
//         <p>You are an administrator.</p>
//     <% } else { %>
//         <p>Welcome, regular user.</p>
//     <% } %>
//     <p>Current time: <%= currentTime.toLocaleTimeString() %></p>
// </body>
// </html>

// Route to render a template file
app.get('/', (req, res) => {
  const userData = {
    user: { name: 'Alice' },
    isAdmin: true,
    currentTime: new Date()
  };
  res.render('index', userData);
});

// Route to render a template string directly
app.get('/direct', (req, res) => {
  const templateString = `<h2>Direct Render</h2><p>Server says: <%= message %></p>`;
  const data = { message: 'Hello from direct EJS render!' };
  const html = ejs.render(templateString, data);
  res.send(html);
});

app.listen(port, () => {
  console.log(`EJS example app listening at http://localhost:${port}`);
  console.log(`Try http://localhost:${port}/ and http://localhost:${port}/direct`);
});

view raw JSON →