pug

Interpolation with Pug

Introduction#

It’s important to be able to use server-side variables in your website. Pug allows you to interpolate data generated by your server in HTML, CSS, and even JavaScript code.

Syntax#

  • res.render(path, variables) // Searches for a pug file to render at path “path”, and passes “variables” to it
  • #{variable} // Interpolates “variable” inline with the surrounding Jade code, after evaluating “variable”
  • !{variable} // Interpolates “variable” inline with the surrounding Jade code, without evaluating “variable”.
  • #[element] // Interpolates “element” inside of an existing Pug HTML element. Syntax of interpolated HTML elements is identical to that of normal HTML elements.

Parameters#

Parameter Details
path Used in res.render. This is the path of the Pug file that we are going to render. The path is taken from the root of the folder set on your Express app: app.set("views", "templates/views"). For example, res.render("index") will search for a Pug file at templates/views/index.pug. Subdirectories can be specified too; res.render("admin/index") looks for a Pug file at templates/views/admin/index.pug.
variables Used in res.render. A JavaScript object of variables to be made accessible to the Pug file defined by path (above). Within the Pug file, the keys of the above JavaScript object become available as variables. If variables = {title: "Hello", color: "red"}, we could use the title and color variable. Subproperties of nested objects are also available.
variable Used in bracket syntax #{} or !{}. The value of variable will be output in the context of its surrounding Pug code. If a pound symbol is prepended to the opening curly bracket, variable will be evaluated before being output. If an exclamation point is prepended to the opening curly brace, variable will not be evaluated.
element Used in square bracket sytax #[]. The HTML element (in Pug syntax, not normal HTML syntax) will be evaluated and output inline with the surrounding Pug code.
## Remarks#
For more information on PugJS interpolation, see the official PugJS interpolation documentation.
## 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).

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>

Raw Variable Interpolation in HTML

Content interpolated with bracket syntax will be evaluated for code, the output of which is included in your HTML output.

title follows the basic pattern for evaluating a template local, but the code in between #{ and } is evaluated, escaped, and the result buffered into the output of the template being rendered. [Source]

If you need to include raw HTML syntax, use an exclamation point instead of a pound symbol (!{} instead of #{}).

index.js

let tag = "<div>You can't escape me!</div>";
res.render("index", {
    myTag: tag
});

index.pug

doctype html
html
    head
    body
        !{myTag}

index.pug output

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <div>You can't escape me!</div>
    </body>
</html>

Value Interpolation in JavaScript Code

Interpolating values is helpful if you need to pass a server-side variable to client-side JavaScript (or other languages that require it).

In the case of variables, numbers, strings, and the like, you can pass these types of variables directly into your JavaScript with bracket syntax plus an explanation point (so that the code inside the brackets is not evaluated.) This is useful for parametrizing JavaScript code that require something from your server.

In the below example, we have to wrap username in quotation marks in order for JavaScript to interpret it as a string; Pug will output the content of the variable as-is, so we need to put it in quotation marks for it to be a proper JavaScript string. This is not necessary for number, where JavaScript will interpret our number as it we intend it to (as a number).

index.js

let number   = 24;
let username = "John";
res.render("index", {
    number:   number,
    username: username
});

index.pug

html
    head
    script.
        // Sets the username of the current user to be displayed site-wide
        function setUsername(username) {
            // ...
        }
        var number   = #{number};
        var username = "#{username}";
        setUsername(username);
        
    body
        p Welcome to my site!

index.pug output

<html>
    <head>
        <script>
            // Sets the username of the current user to be displayed site-wide
            function setUsername(username) {
                // ...
            }
            var number   = 24;
            var username = "John";
            setUsername(username);
        </script>
    </head>
    <body>
        <p>Welcome to my site!</p>
    </body>
</html>

If you need to interpolate the value of a JavaScript object (e.g. all the information about a user), you must stringify the output in Pug for it to be treated as a JavaScript object. It’s also necessary to output the raw contents of the variable, instead of the evaluated form of it. If you were to do output the escaped variable (var user = #{JSON.stringify(user)}), you would receive an escaped version of the object (where quotation marks and apostrophes are converted to &quot;), which is not what we want in order for JSON.stringify to work on it.

index.js

var myUser = {
    name:    "Leeroy Jenkins",
    id:      1234567890,
    address: "123 Wilson Way, New York NY, 10165"
};

res.render('index', {
    user: myUser
});

index.pug

doctype html
html
    head
        script.
            window.onload = function () {
                function setUsername(username) {
                    return username;
                }

                var user = !{JSON.stringify(user)};
                document.getElementById("welcome-user").innerHTML = setUsername(user.name);
            };

    body
        div(id="welcome-user")

index.pug output

<!DOCTYPE html>
<html>
    <head>
        <script>
            window.onload = function() {
                function setUsername(username) {
                    return username;
                }

                var user = {
                    "name": "Leeroy Jenkins",
                    "id": 1234567890,
                    "address": "123 Wilson Way, New York NY, 10165"
                };
                document.getElementById("welcome-user").innerHTML = setUsername(user.name);
        };
        </script>
    </head>
    <body>
        <div id="welcome-user"></div>
    </body>    
</html>

The innerHTML of #welcome-user becomes equal to Leeroy Jenkins. The contents of the user variable are printed directly to the HTML source


HTML Element Interpolation

It may be necessary to nest HTML tags inside of each other. Element interpolation is done in a syntax similar to variable interpolation; square brackets instead of curly braces are used here. The syntax of interpolated HTML elements is identical to the implementation of normal HTML elements.

index.pug

doctype html
html
    head
        title My Awesome Website
    body
        p The server room went #[b boom]!
        p The fire alarm, however, #[u failed to go off...]
        p Not even #[a(href="https://stackoverflow.com/") Stack Overflow] could save them now.

index.pug output

<!DOCTYPE html>
<html>
    <head>
        <title>My Awesome Website</title>
    </head>
    <body>
        <p>The server room went <b>boom</b>!</p>
        <p>The fire alarm, however, <u>failed to go off...</u></p>
        <p>Not even <a href="https://stackoverflow.com/">Stack Overflow</a> could save them now.</p>
    </body>
</html>

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow