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.
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).
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:
npm install pug --save
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:
doctype html html head title A simple pug example body h1 This page is produced by pug template engine p some paragraph here..
Output produced by pug template:
A simple pug example This page is produced by pug template engine
some paragraph here..
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:
doctype html html head title A simple pug example body h1 This page is produced by pug template engine p some paragraph here..
File: server.js
var express = require('express'); var app = express(); //set view engine app.set("view engine","pug") app.get('/', function (req, res) { res.render('view.pug', index); res.render('index'); }); var server = app.listen(5000, function () { console.log('Node server is running..'); });