SyntaxStudy
Sign Up
Express.js Beginner 1 min read

Pug Templates in Depth

Pug's indentation-based syntax eliminates all closing tags and reduces HTML verbosity significantly. Attributes are written in parentheses after the element name, classes use the `.class` shorthand, and IDs use `#id`. Inline text follows the element on the same line; multi-line text uses the pipe (`|`) prefix. Pug supports template inheritance natively through `extends` and `block`. A base layout defines named blocks; child templates override them. This is more powerful than EJS includes because the parent controls the overall structure and children fill in specific sections, preventing duplication of the outer HTML skeleton. Mixins are reusable, parameterised template fragments — the Pug equivalent of a component. Define a mixin once with `mixin card(title, body)` and call it with `+card('Hello', 'World')` anywhere in the template hierarchy. Combining inheritance and mixins produces highly maintainable template code.
Example
//- views/layout.pug
//- doctype html
//- html(lang='en')
//-   head
//-     meta(charset='UTF-8')
//-     title= title + ' | ' + appName
//-     block styles
//-   body
//-     include partials/nav
//-     main.container
//-       block content
//-     include partials/footer
//-     block scripts

//- views/home.pug
//- extends layout
//- block content
//-   h1 Welcome, #{user.name}!
//-   +card('Latest News', 'Check out our updates.')

//- views/mixins.pug
//- mixin card(title, body)
//-   article.card
//-     h2= title
//-     p= body

// Express setup
const express = require('express');
const path    = require('path');
const app     = express();

app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

// Enable view cache in production
if (process.env.NODE_ENV === 'production') {
    app.set('view cache', true);
}

app.use((req, res, next) => {
    res.locals.appName = 'PugDemo';
    next();
});

app.get('/', (req, res) => {
    res.render('home', {
        title: 'Home',
        user:  { name: 'Alice', role: 'admin' },
    });
});

app.listen(3000);