pug Interpolation with Pug Server Side Variable Interpolation


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).


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.


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

index.pug output

<!DOCTYPE html>
        <title>My Cool Website</title>
        <p>My favorite color is Red.</p>
        <p>Here's a list of my favorite coding languages</p>