pug Interpolation with Pug Server Side Variable Interpolation


Example

It's possible to pass variables from your server into Pug for dynamic content or script generation. Pug templates can access variables passed to the res.render function in Express (or pug.renderFile if you are not using Express, the arguments are identical).

index.js

let colors = ["Red", "Green", "Blue"];
let langs  = ["HTML", "CSS", "JS"];
let title  = "My Cool Website";

let locals = {
    siteColors: colors,
    siteLangs:  langs,
    title:      title
};
res.render("index", locals);

Inside your index.pug file, you then have access to the locals variable by way of its keys. The names of the variables in your Pug file become siteColors and siteNames.

To set the entirety of an HTML element equal to a variable, use the equals operator = to do so. If your variable needs to be embedded inline, use bracket syntax #{} to do so.

index.pug

doctype html
html
    head
        title= title
    body
        p My favorite color is #{siteColors[0]}.
        p Here's a list of my favorite coding languages
        ul
            each language in siteLangs
                li= language

index.pug output

<!DOCTYPE html>
<html>
    <head>
        <title>My Cool Website</title>
    </head>
    <body>
        <p>My favorite color is Red.</p>
        <p>Here's a list of my favorite coding languages</p>
        <ul>
            <li>HTML</li>
            <li>CSS</li>
            <li>JS</li>
        </ul>
    </body>
</html>