A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
Some popular template engines that work with Express are Pug, Mustache, and EJS. The Express Application Genreator uses Jade as its default, but it also supports several others.
After the view engine is set, you don’t have to specify the engine or load the template engine module in your app; Express loads the module internally, as shown below (for the above example).
app.set('view engine', 'pug')
Create a Pug template file named index.pug
in the views
directory, with the following content:
html
head
title= title
body
h1= message
Then create a route to render the index.pug
file. If the view engine
property is not set, you must specify the extension of the view
file. Otherwise, you can omit it.
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
When you make a request to the home page, the index.pug
file will be rendered as HTML.
Note: The view engine cache does not cache the contents of the template’s output, only the underlying template itself. The view is still re-rendered with every request even when the cache is on.