Express.js Template Engine
What is a template engine
A template engine facilitates you to use static template files in your applications. At runtime, it replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. So this approach is preferred to design HTML pages easily.
Following is a list of some popular template engines that work with Express.js:
- Pug (formerly known as jade)
- mustache
- dust
- atpl
- eco
- ect
- ejs
- haml
- haml-coffee
- handlebars
- hogan
- jazz
- jqtpl
- JUST
- liquor
- QEJS
- swig
- templayed
- toffee
- underscore
- walrus
- whiskers
In the above template engines, pug (formerly known as jade) and mustache seems to be most popular choice. Pug is similar to Haml which uses whitespace. According to the template-benchmark, pug is 2x slower than Handlebars, EJS, Underscore. ECT seems to be the fastest. Many programmers like mustache template engine mostly because it is one of the simplest and versatile template engines.
Using template engines with Express
Template engine makes you able to use static template files in your application. To render template files you have to set the following application setting properties:
- Views: It specifies a directory where the template files are located.
- view engine: It specifies the template engine that you use. For example, to use the Pug template engine: app.set(‘view engine’, ‘pug’).
For example: app.set(‘views’, ‘./views’).
Let’s take a template engine pug (formerly known as jade).
Pug Template Engine
Let’s learn how to use pug template engine in Node.js application using Express.js. Pug is a template engine for Node.js. Pug uses whitespaces and indentation as the part of the syntax. Its syntax is aesy to learn.
Install pug
Execute the following command to install pug template engine:
Pug template must be written inside .pug file and all .pug files must be put inside views folder in the root folder of Node.js application.
Note: By default Express.js searches all the views in the views folder under the root folder. you can also set to another folder using views property in express. For example: app.set(‘views’,’MyViews’).
The pug template engine takes the input in a simple way and produces the output in HTML. See how it renders HTML:
Simple input:
Output produced by pug template:
Express.js can be used with any template engine. Let’s take an example to deploy how pug template creates HTML page dynamically.
See this example:
Create a file named index.pug file inside views folder and write the following pug template in it:
File: server.js