SyntaxStudy
Sign Up
Express.js Setting Up a Template Engine
Express.js Beginner 1 min read

Setting Up a Template Engine

Express supports any template engine that follows the `(path, options, callback)` interface. The two most popular are Pug (formerly Jade) and EJS. You register a view engine with `app.set('view engine', 'pug')` and tell Express where to find views with `app.set('views', path.join(__dirname, 'views'))`. Calling `res.render('viewName', data)` then locates the file, processes it with the engine, and sends the resulting HTML. Pug uses significant whitespace to represent HTML structure, eliminating closing tags and angled brackets entirely. EJS embeds JavaScript inside `<% %>` tags in otherwise normal HTML, which is easier for developers coming from a PHP background. Both engines support layouts, partials, and template inheritance. The data object passed to `res.render()` is merged with `res.locals`, so values set in middleware (like the current user or flash messages) are automatically available in every template without manually forwarding them on each render call.
Example
// npm install pug ejs

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

// ── Pug engine setup ──────────────────────────────────────────
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

// views/index.pug
// html
//   head
//     title= title
//   body
//     h1 Hello #{user}!
//     ul
//       each item in items
//         li= item

app.use((req, res, next) => {
    res.locals.appName = 'My App'; // available in every template
    next();
});

app.get('/', (req, res) => {
    res.render('index', {
        title: 'Home',
        user:  'Alice',
        items: ['Apple', 'Banana', 'Cherry'],
    });
});

// ── Switch to EJS ─────────────────────────────────────────────
// app.set('view engine', 'ejs');
// views/index.ejs:
// <h1>Hello <%= user %>!</h1>
// <% items.forEach(i => { %><li><%=i%></li><% }); %>

app.listen(3000);