Node.js - Templates - Day Eleven

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. Express uses Jade as its default template engine. Express supports other template engines also, like PUG, Mustache, EJS, Dust.js, Nunjucks.
 
Jade has been renamed to PUG. You can continue to use Jade in your app, and it will work just fine. Each template engine has its own Pros and Cons, such as Jade supports macros and white space significant indentation but not suitable for Non-HTML output.
 
Mustache.js operates on plain HTML, has no significant white space and could be used for things other than HTML, like config files, JSON. But, it has some limitations like no built-in layout support and no Streaming supports.
 
Dust.js supports Async & streaming, Filter supports but it can’t automatically load partials and Preloading and naming templates for rendering feels strange. ejs template engine can be used for things other than HTML, like config files, JSON, and it provides Filters support but no async support. Also, it has very verbose syntax.
 
So, it totally depends upon a company and its requirements what they want to use as their template engine. Even multiple template engines can be used. In this and next upcoming articles, I will prefer to use Jade(PUG) as our template engine and toady, I will explain Jade(PUG) Template Engine.

Install PUG Template Engine

Use “npm install –save pug” to install all dependencies for PUG template engine.

Node.js

After successful installation of PUG packages, now we create set up for “pug” template engine. First, create a “views” folder in your project. In this folder, we will insert all our template layouts.

Node.js

Now, add the following lines in your project.

app.set('view engine', 'pug');
app.set('views', './views');


Node.js

In the first line, we define the view engine for project, which is “pug” template engine for our project. In second line, we define the paths for template layouts, where Express will search for the template layouts.

Now, create a “demo.pug” file in Views folder and add the following code in this file.
  1. doctype html  
  2. html  
  3. head  
  4. title = "Hello Pug"  
  5. body  
  6. h1 This is demo example  
  7. p We implmented Pug template engine  
Node.js

Now, run the application and you will get the following output.

Node.js

What is the role of PUG view engine in this example? Actually, PUG converts the markup language to HTML code. It takes the markup code from “demo.pug” file and renders it to the HTML code. It generates the following HTML code for the “demo.pug” markup code.
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Hello Pug</title>  
  6. </head>  
  7.   
  8. <body>  
  9.     <h1>This is demo example</h1>  
  10.     <p>We implmented Pug template engine</p>  
  11. </body>  
  12.   
  13. </html>  
Sending values to templates

Now, let's learn how to send and use the parameters in templates.

Demo.pug
  1. doctype html  
  2. html  
  3. head  
  4. title Hello Pug "  
  5. body  
  6. h1 = name  
  7. p = city  
  8. p = job  
Index.js
  1. var express = require('express');  
  2. var app = express();  
  3. app.set('view engine''pug');  
  4. app.set('views''./views');  
  5. app.get('/demo'function(req, res) {  
  6.     res.render('demo', {  
  7.         name: " My Nam is Pankaj Choudhary",  
  8.         city: "I live in Alwar",  
  9.         job: "I am working as a Software Developer"  
  10.     });  
  11. });  
  12. app.listen(1400);  
Output

Node.js

In this example, we send some parameters to template file and use the parameters value using "=" (equal) sign. You can also insert the value of parameters into a text line using  #(variable name). Let’s take an example.

Demo.pug
  1. doctype html  
  2. html  
  3. head  
  4. title Hello Pug  
  5. body  
  6. h1 My name is# {  
  7.     name  
  8. }  
  9. p I live in #{  
  10.     city  
  11. }  
  12. pI am working as a# {  
  13.     job  
  14. }  
Index.js
  1. var express = require('express');  
  2. var app = express();  
  3. app.set('view engine''pug');  
  4. app.set('views''./views');  
  5. app.get('/demo'function(req, res) {  
  6.     res.render('demo', {  
  7.         name: " Pankaj Choudhary",  
  8.         city: "Alwar",  
  9.         job: "Software Developer"  
  10.     });  
  11. });  
  12. app.listen(1400);  
Output

Node.js

Indentation is more important in PUG View Engine. It means, all the elements in a template must contain proper indentation otherwise error or unexpected result will be found. The tags that have same indentation must be on same level. For example, if body and head tag have same indentation, so both tags should have the same level. You can use either space or tabs to indent the tags but both at a time. I will prefer to use the “tab” to indent the tags in template. We can put the text inside tag using three methods.

Using Space

h1 My name is Pankaj

Using Pipes

div
My Name is Pankaj | I live in Alwar | I am working as Software Developer

Block of text

div.

My Name is Pankaj.
Working as a Software developer

Attributes in Template

We can assign the list of comma separated attributes for an element, using the parenthesis.

Example

div(style="color:red;font-size:24px",id="div1").
My Name is Pankaj.
Working as a Software developer

The above code will generate the below code in HTML.
  1. <div style="color:red;font-size:24px" id="div1">My Name is Pankaj. Working as a Software developer</div>  
Output

Node.js

Include the Components

PUG provides a better way to manage the reusable code. In PUG, we create a separate file for reusable code and implement that file using the “require” attribute wherever needed. Now, create another “data.pug” file and insert the below data into that file.

My Name is Pankaj.
Working as a Software developer.


Node.js

Demo.pug
  1. doctype html  
  2. html  
  3. head  
  4. title Hello Pug  
  5. body  
  6. div(style = "color:red;font-size:24px", id = "div1")  
  7. include. / data.pug  
Node.js

Output

Node.js

Iterations

PUG supports two types of iterations - Each and While. Let's take one example for each.

Each Loop

ul
each val in ['Alwar','Delhi','Jaipur','Gurgaon']
li=val


Node.js

Output

Node.js

In this example, Each loop generates the list of li elements like below.
  1. <ul>  
  2.     <li>Alwar</li>  
  3.     <li>Delhi</li>  
  4.     <li>Jaipur</li>  
  5.     <li>Gurgaon</li>  
  6. </ul>  
While Loop
  1. //While Loop  
  2. -  
  3. var n = 0;  
  4. ul  
  5. while n < 10  
  6. li = n++  
Node.js

Output

Node.js

The above code generates a list of li elements like previous example but here, we use the While loop instead of Each loop.

Conclusion

In this article, we learned about PUG template engine. Express supports various types of template engines like PUG, Mustache, EJS, Dust.js, Nunjucks. You can use any template engine in your project, as per your requirement.

Thanks for reading the article.

Up Next
    Ebook Download
    View all
    Learn
    View all