Nodejs Template Engine

By ukmodak | April 29th 2021 06:09:08 AM | viewed 551 times

Template Engines for Node.js

Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML.

As per the above figure, client-side browser loads HTML template, JSON/XML data and template engine library from the server. Template engine produces the final HTML using template and data in client's browser. However, some HTML templates process data and generate final HTML page at server side also.

There are many template engines available for Node.js. Each template engine uses a different language to define HTML template and inject data into it.

The following is a list of important (but not limited) template engines for Node.js

  • Jade(pug)
  • Vash
  • EJS
  • Mustache
  • Dust.js
  • Nunjucks
  • Handlebars
  • atpl
  • haml
Advantages of Template engine in Node.js
  1. Improves developer's productivity.
  2. Improves readability and maintainability.
  3. Faster performance.
  4. Maximizes client side processing.
  5. Single template for multiple pages.
  6. Templates can be accessed from CDN (Content Delivery Network).

Jade Template Engine

In this section, you will learn how to use Jade template engine in Node.js application using Express.js.

Jade is a template engine for Node.js. Jade syntax is easy to learn. It uses whitespace and indentation as a part of the syntax.

Install jade into your project using NPM as below.

npm install jade

Jade template must be written inside .jade file. And all .jade files must be put inside views folder in the root folder of Node.js application.

By default Express.js searches all the views in the views folder under the root folder, which can be set to another folder using views property in express e.g. app.set('views','MyViews').

Example: Simple Jade Template

doctype html
html
    head
        title Jade Page
    body
        h1 This page is produced by Jade engine
        p some paragraph here..

The above example will produce following html.

Example: HTML Generated from Above Example




    Jade Page


    

This page is produced by Jade engine

some paragraph here..

Note: Please be careful while giving spaces and indentation in Jade. A small mistake can change the output.

Visit jade-lang.com to learn about jade syntax rules in detail.

Jade Engine with Express.js

Express.js can be used with any template engine. Here, we will use different Jade templates to create HTML pages dynamically.

In order to use Jade with Express.js, create sample.jade file inside views folder and write following Jade template in it.

Sample.jade

doctype html
html
    head
        title Jade Page
    body
        h1 This page is produced by Jade engine
        p some paragraph here..

Now, write the following code to render above Jade template using Express.js.

server.js

var express = require('express');
var app = express();

//set view engine
app.set("view engine","jade")

app.get('/', function (req, res) {

    res.render('sample');

});

var server = app.listen(5000, function () {
    console.log('Node server is running..');
});

As you can see in the above example, first we import express module and then set the view engine using app.set() method. The set() method sets the "view engine", which is one of the application setting property in Express.js. In the HTTP Get request for home page, it renders sample.jade from the views folder using res.render() method.

If you don't set view engine in Express.js then the extension of template must be specified explicitly to res.render() method e.g. res.render('view.jade', data);

Let's look at a complex example. We learned to access SQL server database in the previous section. So, let's fetch all the students' data from SQL Server and render it using jade template.

First of all, create StudentList.jade file inside views folder and write the following template in it.

StudentList.jade

doctype html
html
head
title=title
body
    h1 Student List using Jade engine

    ul
        each item in studentList
            li=item.StudentName

In the above jade template, it uses each loop to generate all the

  • dynamically. Now, render above template in home page request as shown below.

    server.js
    
    var express = require('express');
    var app = express();
    
    app.set("view engine","jade")
    
    app.get('/', function (req, res) {
    
    
        var sql = require("mssql");
    
        var config = {
            user: 'sa',
            password: 'sjkaria',
            server: 'localhost',
            database: 'SchoolDB' 
        };
    
        sql.connect(config, function (err) {
            
            if (err) console.log(err);
    
            var request = new sql.Request();
    
            request.query('select * from Student', function (err, recordset) {
                
                if (err) 
                    console.log(err)
                else
                    res.render('StudentList', { studentList: recordset });
                
            });
        });
    });
    
    

    Run the above example using node server.js command and point your browser to http://localhost:5000 and you will get the following result.

  • bONEandALL
    Visitor

    Total : 18980

    Today :9

    Today Visit Country :

    • Germany
    • Singapore
    • United States
    • Russia