Jade (now Pug) nuggets

Common code snippets for using Pug (formerly Jade) template language.

I often use Pug (aka Jade) for server-side rendering. It is powerful, succinct and beats writing HTML any day. Here are my common code snippets.

Set template language in Express

Install and save Pug module

npm install --save pug

Create a folder for your views, for example views. Then place template files there

views/
    index.pug
    about.pug
app.js

Set the template language in the Express app (note that you don't need to actually require the pug module itself - all happens automatically)

1
2
3
app.set('view engine', 'pug')
app.set('views', './views')
app.locals.pretty = true // indent produces HTML for clarity

The to render about page

1
2
3
4
5
6
7
app.get('/about', function (req, res, next) {
// res.render(<template file/view name>, <data object>)
const aboutData = {
author: 'Gleb'
}
res.render('about', aboutData)
})

Iterate over a list

See the latest detailed documentation for Jade iteration at jade-lang.com. Pass a list inside the data object and then use each <var> in <list> to iterate

1
2
3
ul
each person in people
li #{person.name} - #{person.gender}

Inject constants for front end web application

I have described how to inject Angular configuration in this blog post and how to use Jade as primary template language for Angular. I just want to remind everyone that sometimes safe injection leads to security issues. My primary recommendation is to use content security policy and run with inline JavaScript disabled.