Nunjucks

Nunjucks is rich and powerful template engine for JavaScript. Nunjucks is developed by Mozilla and is maintained by Node JS Foundation. Nunjucks can be used in Node and browser. Its is inspired by Jinja2 ( a web template engine for python ).

In node, Nunjucks is installed using npm. Its is rich, fast, extensible and available everywhere. It's just 8kb gzipped.

Advantages

  1. Rich templating language with block inheritance, autoescaping, macros, asynchronous control, etc.
  2. Fast and Lean High-performant. Small 8K gzipped runtime with precompiled templates in the browser
  3. Extensible easily extensible with custom filters and extensions
  4. Everywhere Available in node and all modern web browsers, with precompilation options

Install Nunjucks

To install Nunjucks, type npm i nunjucks.

npm i nunjucks


Configure Nunjucks

Build a index.html file for static html page in views folder of src folder in root directory. Nunjucks configuration can be done for both node and express. See example

Configure in Node


const nunjucks=require("nunjucks");

// configure
nunjucks.configure('views', { autoescape: true });
nunjucks.render('index.html', { name: 'nunjucks' });

Configure in Express


const express=require("express");
const path=require("path");
const nunjucks=require("nunjucks");
const app=express();

app.use(express.static(path.resolve(__dirname,'assets')));

// configure
nunjucks.configure(path.resolve(__dirname,'views'),{
    express:app,
    autoscape:true,
    noCache:false,
    watch:true
}); 

app.get("/",(req,res)=>{
    res.render('index.html',{});
});

app.listen(3000,()=>{
    console.log("express server running on ", 3000)
})

Templating

Nunjucks supports many powerful features for templating.

Nunjucks supports any file extension, like .njk or .html. In this tutorial, we are using .html extension for all static html files placed in views folder of src directory in root.

Nunjucks Directory Structure


    nodeapp/
    ├── package.json
    ├── package-lock.json
    ├── src/
    │   ├── assets/
    │   │     └─── style.css
    │   │       
    │   ├── views/
    │   │    ├─── index.html
    │   │    ├─── header.html
    │   │    └─── footer.html
    │   │ 
    │   └─── server.js
    └── node_modules/
      

Variables

Variables declared in template context is used within {{}} in html. See example

We are using nunjucks version 3.2.1 licenced under Mozilla.

    /*server.js*/

app.get("/",(req,res)=>{
    res.render('index.html',{
        name:'nunjucks',
        data:{
            version:'3.2.1',
            licence:'Mozilla'
        },
    });
});    
    /*index.html*/

   <p>We are using {{name}} version {{data.version}} licenced under {{data['licence']}}.</p>   

Filter

Nunjucks filters are used to filter data declared in template context. Filters can be both buildin and custom filters. To call a filter, use pipe (|) operator. Se examples.

Name is Avinash


     <p> Name is {{"avinash" | title }}</p>

Data is 1-2-3


     <p> Data is  {{ [1,2,3] | join('-') }}</p>

username


     <p>  {{ "user" | replace('user',"username") }}</p>

Template Inheritance

We can use include and extend to reuse template components. This is called Template Inheritance.

    /* index.html */
<div class="container">    
    {% include "header.html" %}
    {% include "main.html" %}
    {% include "footer.html" %}
</div>    
    
 /* header.html */
   
<header>
    <h1>Header</h1>
</header>
    
 /* main.html */
   
<section>
    <h2>Section</h2>
</section>
    
 /* footer.html */
   
<footer>
    <p>© 2020</p>
</footer>
    

Final Output of index.html


<div class="container">
    <header>
        <h1>Header</h1>
    </header>
    <section>
        <h2>Section</h2>
    </section>
    <footer>
        <p>© 2020</p>
    </footer>    
</div">    

For

For is used to traversal data from Arrays and Objects.

For Array


    <ol>
        {% for i in month %}   
             <li>{{ i }}</li>
        {% endfor %}    
    </ol>

For Object


    <ol>
        {% for i,j in user %}   
             <li>{{ i }}</li>
        {% endfor %}    
    </ol>

If

if is used to test a condition like in JavaScript. For conditions, use elif ( same like elseif ) or else after if.

if


    {% if name %}
           name
    {% endif %}

elif


    {% if name %}
        data1
    {% elif %}  
        data2        
    {% endif %}

else


    {% if name %}
        name
    {% else %}
        name not available         
    {% endif %}

Math

We can also use mathematical operators in Nunjucks. Here are supported operators

  1. Addition:
    +
  2. Subtraction:
    -
  3. Multiplication:
    *
  4. Division:
    /
  5. Division Remainder:
    %
  6. Power:
    **

Comparision

The following Operators are supported in Nunjucks.

  1. Comparision:
    ==
  2. Strict Comparision:
    ===
  3. Greater than:
    >
  4. Less than:
    <
  5. Greater than equals:
    >=
  6. Less than equals:
    <=
  7. Not equals:
    !=
  8. Strict Not equals:
    !==

Logic Operators

Following Logical Operators are also supported.

  1. and
    and
  2. or
    or
  3. not
    not