7 JavaScript Templating Engines with Code Examples

JavaScript templating engines enable you to add dynamic logic to static HTML pages. For instance, you can declare a variable that the engine replaces with an actual value at runtime. Similarly, you can use conditionals, loops, filters, mixins, and other constructs, depending on the templating engine you choose.

Besides significantly speeding up front-end development, JavaScript templating engines also make debugging and maintenance simpler and faster. Each engine comes with its own syntax that you need to learn. However, the learning curve is usually pretty flat, as template syntaxes are purposefully straightforward and easy to memorize.

In this article, we have collected seven JavaScript templating engines you can use in your everyday workflow. The code examples have been hand-picked from the documentation of the respective template engine.

1. Nunjucks

7 JavaScript Templating Engines with Code Examples

Nunjucks is a high-performant, full-featured JavaScript templating engine, inspired by the Jinja2 templating engine for Python. It has been developed and maintained by Mozilla who also uses Nunjucks for its own products like Firefox Marketplace and Mozilla Webmaker. Nunjucks comes with many advanced features such as built-in filters, keyword arguments, template inheritance, asynchronous templates, and more. 

You can add Nunjucks to your project either with npm or by adding the nunjucks.js library to your HTML page. Nunjucks supports all modern browsers, however, you need to use ES5-shim to support Internet Explorer 8.

Nunjucks template example (template inheritance):

Parent template:

{% block header %}
This is the default content
{% endblock %}

<section class="left">
{% block left %}{% endblock %}
</section>

<section class="right">
{% block right %}
This is the right side!
{% endblock %}
</section>

Child template:

{% extends "parent.html" %}

{% block left %}
This is the left side!
{% endblock %}

{% block right %}
This is the right side!
{% endblock %}

Output:

This is the default content

<section class="left">
This is the left side!
</section>

<section class="right">
This is the right side!
</section>

2. Pug

7 JavaScript Templating Engines with Code Examples

Pug was formerly known as Jade but the dev team had to rename it when it turned out that Jade was a registered trademark. If you have used Haml before, you will be familiar with Pug, as it was heavily inspired by it. Pug allows you to rapidly write static templates. The Pug syntax includes conditionals, filters, includes, iterations, mixins, interpolation, and other logic constructs.

It fully integrates with Express.js as a supported view engine. If you want to use your Pug templates in React development, you can transpile them to JSX using this Babel plugin, too. You can also develop WordPress themes using Pug templates with the help of the Wordless plugin. It adds Pug, Sass, CoffeeScript, and Webpack to your WordPress theme.

Pug template example (conditionals):

Template:

var user = { description: 'foo bar baz' }
var authorised = false
#user
    if user.description 
        h2.green Description
        p.description= user.description
    else if authorised
        h2.blue Description
        p.description.
             User has no description,
             why not add one...
    else
        h2.red Description
        p.description User has no description

Output:

<div id="user">
    <h2 class="green">Description</h2>
    <p class="description">foo bar baz</p>
</div>

3. Mustache.js

7 JavaScript Templating Engines with Code Examples

Mustache.js is the JavaScript implementation of the popular {{mustache}} template system. Besides JavaScript, {{mustache}} is also available in Ruby, PHP, C#/.NET, Android, C++, and many other programming languages. It’s an excellent choice for developers who code in multiple languages, as you need to pick up the syntax only once.

Templates created with {{mustache}} are logicless, as the syntax has no if-else statements, for loops, and similar logic—only template tags. To use Mustache.js, you need to define a view object for the data and a template. Mustache.js is used by many notable companies such as LinkedIn, Twitter, PayPal, and Buzzfeed.

Mustache template example (non-empty lists):

View:

  "beatles": [
    { "firstName": "John", "lastName": "Lennon" },
    { "firstName": "Paul", "lastName": "McCartney" },
    { "firstName": "George", "lastName": "Harrison" },
    { "firstName": "Ringo", "lastName": "Starr" }
  ],
  "name": function () {
    return this.firstName + " " + this.lastName;
  }
}

Template:

{{#beatles}}
* {{name}}
{{/beatles}}

Output:

* John Lennon
* Paul McCartney
* George Harrison
* Ringo Starr

4. Handlebars

7 JavaScript Templating Engines with Code Examples

The Handlebars engine allows you to build semantic templates similar to Mustache templates. In most cases, you can use Mustache and Handlebars templates in place of each other, however there are some exceptions as well. The Handlebars syntax is a superset of Mustache. It extends the Mustache syntax with some extra features that make template creation easier.

With Handlebars, you can use nested paths while Mustache only supports simple paths. The Block Expression feature enables you to create helpers that call your template in different contexts. You can also pass literal values to helpers as arguments, including strings, numbers, boolean values, null, and undefined. According to performance tests, the current version of Handlebars (Handlebars 4) is 5 to 7 times faster than its Mustache equivalent.

Handlebars template example (helpers):

Template:

<div class="post">
  <h1>By {{fullName author}}</h1>
  <div class="body">{{body}}</div>

  <h1>Comments</h1>

  {{#each comments}}
  <h2>By {{fullName author}}</h2>
  <div class="body">{{body}}</div>
  {{/each}}
</div>

Context and helpers:

var context = {
  author: {firstName: "Alan", lastName: "Johnson"},
  body: "I Love Handlebars",
  comments: [{
    author: {firstName: "Yehuda", lastName: "Katz"},
    body: "Me too!"
  }]
};

Handlebars.registerHelper('fullName', function(person) {
  return person.firstName + " " + person.lastName;
});

Output:

<div class="post">
  <h1>By Alan Johnson</h1>
  <div class="body">I Love Handlebars</div>

  <h1>Comments</h1>

  <h2>By Yehuda Katz</h2>
  <div class="body">Me Too!</div>
</div>

5. Template7

7 JavaScript Templating Engines with Code Examples

Template7 is a JavaScript templating engine that follows a mobile-first approach. It has been created and maintained by the team behind the popular Framework7 mobile framework that allows you to build iOS and Android applications. Template7 is also used as the default template engine in Framework7. It has a similar syntax to Handlebars but it’s around 2-3 faster. Template7’s is also pretty lightweight; the minified and gzipped version weighs only 1KB.

With Template7, you can embed Handlebars expressions into regular HTML files. It also has built-in helpers that make it easy to dynamically process content. For instance, you can use {{#each}}…{{else}}..{{/each}}, {{#if}}…{{else}}…{{/if}}, {{#unless}}…{{else}}…{{/unless}}, and other block expressions as helper functions. Template7 lets you define custom helpers and reuse templates through partials, too.

Template7 template example (unordered list):

Template:

<p>Here are the list of people I know:</p>
<ul>
  {{#each people}}
  <li>{{firstName}} {{lastName}}</li>
  {{/each}}
</ul>

Context:

 people : [
    {
      firstName: 'John',
      lastName: 'Doe'
    },
    {
      firstName: 'Mark',
      lastName: 'Johnson'
    },
  ]
}

Output:

<p>Here are the list of people I know:</p>
<ul>
  <li>John Doe</li>
  <li>Mark Johnson</li>
</ul>

6. JsRender

7 JavaScript Templating Engines with Code Examples

JsRender is an extensible JavaScript template engine you can use in different ways. It allows you to render templates both on a (Node.js) server and in the browser. You can load it with or without jQuery. The Node.js version also provides you with built-in Express, Hapi, and Browserify integration.

JsRender uses a Mustache-like syntax where you need to insert template tags within a pair of double curly brackets {{…}}. The syntax includes evaluations, partials, loops, conditionals, loops, iterations, and other logical constructs.

You can also create custom tags and extend default template tags, for instance, the {{for}} tag. The JsRender syntax contains helpers and converters (e.g. uppercase converter), and rich expressions to facilitate creating complex logic, too.

JsRender template example (conditionals):

Template:

<div>
   <em>Name:</em> {{:name}}
   {{if showNickname && nickname}}
      (Goes by <em>{{:nickname}}</em>)
   {{/if}}
</div>

Data:

[
  {
    "name": "Robert",
    "nickname": "Bob",
    "showNickname": true
  },
  {
    "name": "Susan",
    "nickname": "Sue",
    "showNickname": false
  }
]

Output:

<div>
    <em>Name:</em> Robert (Goes by <em>Bob</em>)
</div>
<div>
    <em>Name:</em> Susan
</div>

7. doT.js

7 JavaScript Templating Engines with Code Examples

The doT.js JavaScript templating engine puts focus on speed and performance. You can use it either with npm or by adding the JS library to your HTML page. doT.js has no dependencies and loads even large templates fairly fast (you can run a live speed test here). You can choose between runtime and compile time evaluation. It’s worth opting for the latter when your data don’t change with each run of the template.

The default doT syntax refers data with the it variable name (see in the example below). However, you can change it by editing the compilation settings file. The syntax allows you to use partials, conditionals, arrays, interpolation, loops, and other logic. Many developers use doT together with Express.js, too.

 doT.js template example (interpolation):

Template:

<div>Hi {{=it.name}}!</div>
<div>You are {{=it.age || ''}} today!</div>

Data:

Output:

<div>Hi Jake!</div>
<div>You are 31 today!</div>

Next Steps

JavaScript templating engines can save you a lot of time and manual work. As an alternative, you can use ES6 template literals, however, most template engines have much more options and capabilities.

Besides template engines, you can also speed up your development workflow with front-end frameworks that provide you with a pre-defined structure and handle several common tasks. If you need some motivation to get started with JS frameworks, have a look at our hand-picked tools & resources collections for the React.js and Vue.js frameworks, too.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.