Express: Template engines

Express is capable of handling server-side template engines.

Template engines allow us to add data to a view, and generate HTML dynamically.

Express uses Jade as the default.

Jade is the old version of Pug, specifically Pug 1.0.

The name was changed from Jade to Pug due to a trademark issue in 2016, when the project released version 2. You can still use Jade, aka Pug 1.0, but going forward, it’s best to use Pug 2.0

Although the last version of Jade is 3 years old (at the time of writing, summer 2018), it’s still the default in Express for backward compatibility reasons.

In any new project, you should use Pug or another engine of your choice, like EJS, Handlebars, or any other supported template engine.

Let’s see the basics of Pug now. The official site of Pug is https://pugjs.org/.

You can use many different template engines, including Pug, Handlebars, Mustache, EJS and more.

To use Pug we must first install it:

npm install pug

and when initializing the Express app, we need to set it:

const express = require('express')
const app = express()
app.set('view engine', 'pug')

We can now start writing our templates in .pug files.

Create an about view:

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

and the template in views/about.pug:

p Hello from Flavio

This template will create a p tag with the content Hello from Flavio.

You can interpolate a variable using

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

Look at the Pug guide for more information on how to use Pug.

This online converter from HTML to Pug will be a great help: https://html-to-pug.com/

Lessons in this unit:

0: Introduction
1: Introduction to Express
2: Request parameters
3: Send a response to the client
4: Send a JSON response
5: Manage cookies
6: Work with HTTP headers
7: Handling redirects
8: Routing
9: ▶︎ Template engines
10: Middleware
11: Serving Static Assets with Express
12: Send files to the client
13: Sessions
14: Validating and sanitizing input
15: Handling form data
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!