/

The Pug Guide: A Comprehensive Introduction to the Pug Templating Engine

The Pug Guide: A Comprehensive Introduction to the Pug Templating Engine

tags: [“Pug”, “template engine”, “Express”, “Node.js”, “Jade”]

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”:

1
p Hello from Flavio

Install Pug

Installing Pug is as simple as running the following command:

1
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:

1
2
3
4
5
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”:

1
2
3
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”:

1
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:

1
2
3
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:

1
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:

1
2
3
app.get('/about', (req, res) => {
res.render('about', { getName: () => 'Flavio' })
})
1
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:

1
2
p#title
p.title

Set the doctype

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

1
doctype html

Meta tags

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

1
2
3
4
5
6
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:

1
2
3
4
5
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:

1
2
3
4
5
6
7
8
9
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:

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

Conditionals

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

1
2
3
4
if name
h2 Hello from #{name}
else
h2 Hello

Set variables

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

1
2
3
4
- 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:

1
age++

Assigning variables to element values

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

1
p= name
1
span.age= age

Iterating over variables

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

1
2
for dog in dogs
li= dog
1
2
3
ul
each dog in dogs
li= dog

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

1
p There are #{values.length}

Including other Pug files

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

1
include otherfile.pug

Defining blocks

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

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
7
8
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:

1
// some comment

Block:

1
2
3
//
some
comment

Invisible comments

Inline:

1
//- some comment

Block:

1
2
3
//-
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.