Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Variables and interpolation

A template becomes useful once it has data: the café name, prices, the year in the footer. In Pug you can write lines of plain JavaScript and insert their results into the markup.

A code line and output with =

A line starting with - and a space is JavaScript that runs at build time and outputs nothing. Declare a variable in src/index.pug and output it:

- const cafe = "Morning Café"
h1= cafe

An = right after the tag means the content of the tag is the value of the expression, not text:

<h1>Morning Café</h1>

Inserting into text

To put a value in the middle of text, use #{...}:

- const cafe = "Morning Café"
- const price = 3
p Welcome to #{cafe}!
p Two cappuccinos cost $#{price * 2}.

Inside the braces goes any JavaScript expression, and its result takes the place of the insertion:

<p>Welcome to Morning Café!</p>
<p>Two cappuccinos cost $6.</p>

A variable in an attribute

An attribute value is an expression too, so a variable is written without quotes:

- const menuUrl = "menu.html"
a(href=menuUrl) See the menu

Pug inserted the value of the variable:

<a href="menu.html">See the menu</a>

Several lines of code

When there is more than one line of code, put - on its own line and indent the code below it:

-
  const drinks = ["Espresso", "Cappuccino", "Hot chocolate"]
  const count = drinks.length
p Drinks on the menu today: #{count}.

The whole indented block runs as JavaScript:

<p>Drinks on the menu today: 3.</p>

Data from the build script

Data usually comes from outside. Everything you pass to pug.renderFile() together with the options becomes a template variable. Change the call in build.js:

// build.js
const html = pug.renderFile("src/index.pug", {
  pretty: true,
  year: 2026,
  phone: "+1 555 0100",
});

Now the variables year and phone are available in src/index.pug without declaring them:

footer
  p © #{year} Morning Café
  p Phone: #{phone}

After npm run build the footer shows the year and the phone number:

<footer>
  <p>© 2026 Morning Café</p>
  <p>Phone: +1 555 0100</p>
</footer>

Values inserted with = and #{...} are escaped by Pug: the characters < and > become &lt; and &gt;, so text from the data cannot turn into a tag. More on that in the next lesson.

Common mistake

Forgetting = or #{...}:

- const cafe = "Morning Café"
h1 cafe

Plain text follows the space, so the heading shows the word, not the value of the variable:

<h1>cafe</h1>

Write h1= cafe or h1 #{cafe}.

Thanks for reading!

Donate to the site — we work hard for you.