(A Comprehensive Handlebars.js Tutorial)

This is a complete tutorial, and indeed a reference, on Handlebars.js templating and, principally, JavaScript templating. Handlebars.js is a client-side (though it can be used on the server, too) templating engine for JavaScript. It is a JavaScript library that you include in your page just as you include any other JavaScript file. And with it, you can add templates to your HTML page that will be parsed and interpolated (values of properties inserted in place) with the values from the data you passed to the Handlebars.js function.

[sc:mongodb-book]

Written in JavaScript, Handlebars.js is a compiler that takes any HTML and Handlebars expression and compiles them to a JavaScript function. This derived JavaScript function then takes one parameter, an object—your data—and it returns a string with the HTML and the object properties’ values inserted into the HTML. So, you end up with a string that has the values from the object properties inserted in the relevant places, and you insert that string as HTML on the page.

Do I Have To Use a JavaScript Templating Engine? If so, Why?

Yes. If you develop or plan to develop JavaScript applications, you should use a JavaScript client-side templating engine to keep your JavaScript and HTML sufficiently decoupled; that is, keep your HTML separate from your JavaScript, which allows you to manage your HTML and JS files reliably and easily.

Sure, you can use JSDom, or you can fire up server-side templating and send your HTML files via HTTP. But I recommend client-side templating because it typically executes faster than server-side templating and it provides the easiest way to create and maintain your templates.

In addition, just about all the JavaScript front-end frameworks use a JavaScript templating engine, so you will eventually use JavaScript templating because you will likely use a JavaScript front-end or backend framework.

When to Use a JavaScript Templating Engine and Why to Use Handlebars.js?

The answers to both of these questions follow. Indeed, there exist some specific use cases for JavaScript templating engines.

When To Use a JavaScript Templating Engine?

You should use a JavaScript templating engine like Handlebars.js when:

  • You use a JavaScript front-end framework like Backone.js, Ember.js, and the like; most front-end JavaScript frameworks rely on templating engines
  • The application’s view (the HTML page or portions of the page) will be updated frequently, especially as a result of changes to the data either from the server via a REST API or from data on the client
  • You have multiple tech stacks that depend on your data from the server and you want all the tech stacks to process the same data
  • Your application has much interactivity and it is very responsive
  • You are developing a single-page web application with multiple views
  • You want to easily manage your HTML content; you don’t want your JavaScript code to contain important HTML markup. Here is an example of JS code with HTML markup (it makes it difficult to manage your HTML markup):
    shoesData.forEach (function (eachShoe)  {
    //Note the intermingling of HTML and JavaScript; it is tedious to follow:
    theHTMLListOfShoes += '
  • ' + '' + eachShoe.name + ' -- Price: ' + eachShoe.price + '
  • '; }); return theHTMLListOfShoes; }

Why Use Handlebars.js (out of the eight or more templating engines)?

Unsurprisingly, there are many JavaScript client-side templating engines, but we will focus on only Handlebars.js in this tutorial, since it is the best of the lot. Some of the other worthy templating engines are Underscore.js’ Template, Mustache.js, EJS, and Dust.js.

Handlebars.js is an extension of the Mustache JavaScript templating language; it supersedes Mustache.js.

The reasons you should use Handlerbars.js follow:

  • Handlebars is one of the most advanced (pre-compiling and the like), feature-rich, and popular of all the JavaScript templating engines, and it has the most active community.
  • Handlebars is a logic-less templating engine, which means there is little to no logic in your templates that are on the HTML page. The most important use of Handlebars, and any templating engine, is to keep your HTML pages simple and clean and decoupled from the logic-based JavaScript files, and Handlebars serves this purpose well. Indeed, Dust.js is also a logic-less templating engine and a worthy alternative to Handlebars.js.
  • Moreover, the cutting-edge JavaScript frameworks Meteor.js and Derby.js, which we will cover in upcoming posts, are expected to become mainstream in the coming months, and both use Handlebars.js. To be clear: Meteor.js uses Handlebars.js and Derby.js “template syntax is largely based on Handlebars” template syntax. And Ember.js uses Handlebars, too.

    While Backbone.js is packaged with Underscore.js templating engine, it is super easy to use Handlebars.js with Backbone.js.

    Therefore, the experience and knowledge you will have gained from learning Handlebars.js now will be well worth it, if you use, or plan to use, any of the noted JS frameworks.

In short, learning Handlebars.js now is an investment and a wise choice: you will program more effectively now and you will adapt easily to the JS frameworks tomorrow and in the coming weeks and months.

Handlebars.js Overview

Now that we have seen how to use Handlebars in a simple application, let’s study Handlebars in detail.

How Handlebars.js Works?

As noted in the introduction: Handlebars.js is a compiler built with JavaScript that takes any HTML and Handlebars expression and compiles them to a JavaScript function. This derived JavaScript function then takes one parameter, an object—your data—and it returns an HTML string with the object properties’ values inserted (interpolated) into the HTML. So, you end up with a string (HTML) that has the values from the object properties inserted in the relevant places, and you insert the string on a page.

This sounds way more complex that it is, so let’s take a closer look.

The 3 Main Parts of Handlebars Templating

To use Handlebars, first you link to the Handlebars.js file in the head block of your HTML page, just like you do for jQuery or any .js files.. Then there are 3 main pieces of code you use for Handlebars templating:

<

ol>

  • Handlebars.js Expressions
    A simple Handlebars expression is written like this (where “content” can be a variable or a helper function with—or without—parameters:
    {{ content }} 
    

    Or like this, in the case of Handlebars block expressions (which we will discuss in detail later):

    {{#each}} 
    HTML content and other Handlebars expresion go here.
    {{/each}}
    

    Below is a Handlebars expression with HTML. The customerName variable is the property that will be interpolated (its values will be inserted in place) by the Handlebars.compile function:

    Name: {{ customerName }}

    The output will be the following (if the customerName variable has the value “Richard”):

    Richard

    Since you have to pass the Handlebars expression (with any containing HTML) to the Handlebars.compile function, a script tag is used to enclose each Handlebars template when they are on the HTML page. Indeed, the script tag is not necessary when a template is in its own HTML file, but it is necessary when the Handlebars template is on the page along with other Handlebars template and other HTML content.

    — Script Tag
    Handlebars templates are embedded in script tags (where the script tag’s type property is set to “text/x-handlebars-template”). The script tag is similar to the script tag you normally use to embed JavaScript in the HTML page, except the type attribute is different. You retrieve the HTML content from the script tag and pass it to the Handlebars compiler.

    Here is an example of the Handlebars script tag: