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