Introduction to Pug

Pug is a template engine designed for server-side Node.js applications. It allows developers to add dynamic data to views and generate HTML. Formerly known as Jade 2.0, the project changed its name to Pug in 2016 due to a trademark issue. While the older version (Jade 1.0) is still usable, it is recommended to use the latest version (Pug 2.0). Learn more about the differences between Jade and Pug.

How does Pug look?

In Pug, tags and their content are specified differently compared to other template engines. For example, the following Pug code creates a <p> tag with the content “Hello from Flavio”:

p Hello from Flavio

Install Pug

Installing Pug is as simple as running the following command:

npm install pug

Setup Pug to be the template engine in Express

To use Pug as the template engine in an Express application, you need to set it up in the following way:

const path = require('path')
const express = require('express')
const app = express()
app.set('view engine', 'pug')
app.set('views', path.join(__dirname, 'views'))

Your first Pug template

Here’s an example of creating an “about” route that renders a Pug template named “about.pug”:

app.get('/about', (req, res) => {
 res.render('about')
})

The “about.pug” template contains the following code, which creates a <p> tag with the content “Hello from Flavio”:

p Hello from Flavio

Interpolating variables in Pug

You can interpolate variables in Pug templates by passing them as an object during rendering. For example:

app.get('/about', (req, res) => {
 res.render('about', { name: 'Flavio' })
})

And in the Pug template, you can interpolate the value of the “name” variable using the #{} syntax:

p Hello from #{name}

Interpolate a function return value

To interpolate the return value of a function in Pug, pass the function in the rendering step and use the #{} syntax to interpolate its result:

app.get('/about', (req, res) => {
 res.render('about', { getName: () => 'Flavio' })
})
p Hello from #{getName()}

Adding id and class attributes to elements

To add id and class attributes to elements, use the following syntax in Pug:

p#title
p.title

Set the doctype

To specify the HTML doctype in Pug, use the following syntax:

doctype html

Meta tags

To add meta tags to your Pug template, use the following syntax:

html
 head
  meta(charset='utf-8')
  meta(http-equiv='X-UA-Compatible', content='IE=edge')
  meta(name='description', content='Some description')
  meta(name='viewport', content='width=device-width, initial-scale=1')

Adding scripts and styles

To include external scripts and stylesheets in your Pug template, use the following syntax:

html
 head
  script(src="script.js")
  script(src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')
  link(rel='stylesheet', href='css/main.css')

Inline scripts

To include inline scripts in your Pug template, use the following syntax:

script alert('test')

script.
 (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
 function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
 e=o.createElement(i);r=o.getElementsByTagName(i)[0];
 e.src='//www.google-analytics.com/analytics.js';
 r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
 ga('create','UA-XXXXX-X');ga('send','pageview');

Loops

To iterate over an array in Pug, use the each keyword:

ul
 each color in ['Red', 'Yellow', 'Blue']
  li= color

Conditionals

To use conditionals in Pug, use the if, else if, and else keywords:

if name
 h2 Hello from #{name}
else
 h2 Hello

Set variables

You can set variables in Pug templates using the - var syntax:

- var name = 'Flavio'
- var age = 35
- var roger = { name: 'Roger' }
- var dogs = ['Roger', 'Syd']

Incrementing variables

To increment a numeric variable in Pug, you can use the ++ operator:

age++

Assigning variables to element values

To assign variables to element values in Pug, use the following syntax:

p= name
span.age= age

Iterating over variables

To iterate over variables in Pug, you can use either the for or each keyword:

for dog in dogs
 li= dog
ul
 each dog in dogs
  li= dog

To get the number of items in an array, use the .length property:

p There are #{values.length}

Including other Pug files

To include other Pug files in your template, use the include keyword:

include otherfile.pug

Defining blocks

To define blocks in Pug, which can be overridden by extending templates, use the block keyword:

html
 head
  script(src="script.js")
  script(src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')
  link(rel='stylesheet', href='css/main.css')
  block head
 body
  block body
  h1 Home page
  p welcome

Extending a base template

To extend a base template in Pug, use the extends keyword and redefine the necessary blocks:

extends home.pug

block body
 h1 Another page
 p Hey!
 ul
  li Something
  li Something else

Comments

Pug supports both visible and invisible comments. Visible comments are rendered in the resulting HTML, while invisible comments are not.

Visible comments

Inline:

// some comment

Block:

//
 some
 comment

Invisible comments

Inline:

//- some comment

Block:

//-
 some
 comment

Now that you have a comprehensive guide to using the Pug templating engine, you can start building dynamic and efficient websites with Node.js applications.