Beginner’s Guide to Using Handlebars.js

In this post, we are going to look into Handlebars, a JavaScript templating engine based on Mustache. It shares the same functionalities with Mustache but sports several new features. Handlebars is a handy templating tool, particularly for displaying data series in JSON format, which today is a common data-formatting form used in web application APIs. Check out this introductory post, which explains JSON really well.

In this article, we are going to walk you through some of Handlebars’ basic functionalities, and we will also work on a real example at the end. If this is something you want to get to know, then let’s get started.

Getting Started

To start off, let’s go to the Handlebars website and download the source code file, handlebars.js. Put the file in an appropriate folder within your project. Link the file from your HTML documents. You can add the link inside the <head> tag or before the closing </body> tag.

  <script src="js/handlebars.js"></script>

Alternatively, you can also link to the Handlebars source from a CDN.

  <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script>

Once that’s done, we can start creating a template.

Basic Template

Let’s add our data: a name, age, and where the person comes from.

  var dataSource = {
    "name": "Joe Bloggs",
    "age": "19",
    "from": "United Kingdom"
  }

This data serves as an example. As mentioned, you can retrieve similar forms of data from most web applications that provide an open API, such as Twitter, Instagram, Flickr, and Dribbble – though you’ll likely get more lines of data than shown above. Alternatively, you can try JSON Generator to generate some random data.

The Template

Once we have the data, we can create the template to place these data. Let’s look at the following code.

  <div id="content" class="content-wrap">
    <script id="template" type="text/x-handlebars-template">
      <p>Hi, I'm {{name}}. I'm {{age}}, and I'm from {{from}}</p>
    </script>
  </div>

A Handlebars template is set within a <script> tag with a special type: text/x-handlebars-template, and preferably also with an ID, because selecting an element by ID in JavaScript is technically more straightforward and faster than using a class.

Each piece of data is declared within double curly braces, {{...}}; this is also known as a Handlebars expression.

However, before we can see the result in the browser, we have to compile these codes, merging the data into the template.

Compiling

Let’s store the template in a JavaScript variable, like so.

  var template = $('#template').html();

We then pass the template variable into Handlebars.compile() to compile the template.

  var compile = Handlebars.compile(template);

The most important part of the above code is the variable’s name, compile. We will use it along with our data to generate the final result, like so:

  var result = compile(dataSource);

Lastly, we put it into the #content element using the jQuery .html() method this way.

  $('#content').html(result);

This will give us the following result in the browser:

Handlebars basic output example

HTML Escaping

Sometimes our data might contain HTML tags, for example:

  var dataSource = {
    "name": "<em>Joe Bloggs</em>",
    "age": "19",
    "from": "United Kingdom"
  }

By default, Handlebars will escape these tags. It will turn the tags into their HTML entities: < becomes < and > becomes >. This will result in an unexpected output in the browser, as shown below:

Handlebars HTML escaped output

To prevent Handlebars from converting HTML tags into entities and instead treat them as actual HTML, use triple curly braces {{{...}}} to declare the data, like so:

  Hi, My name is {{{name}}}. ...

There you go! The heading tag is now rendered correctly, and the name is displayed in italics.

Handlebars HTML unescaped output

Conditional Helper

Handlebars supports conditional helpers (also known as conditional functions). This feature is an exclusive addition to Handlebars, not available in Mustache. A conditional helper is useful for preventing data rendering if the value is empty. As an example, let’s remove the value from our age data.

  var dataSource = {
    "name": "Joe Bloggs",
    "age": "",
    "from": "United Kingdom"
  }

We use the conditional helper like this. Since the age value is not present, the line `I’m {{age}},` will not be displayed.

  {{#if age}}I'm {{age}},{{/if}}

In the browser, the line mentioned above will not be rendered.

Handlebars conditional helper output

Additionally, Handlebars will treat the data as empty if the value is explicitly set to undefined or false.

Loop

Handlebars also supports loops. As in other programming languages, loops are used to iterate over a series of objects. Currently, we only have one object containing three lines of data. Let’s extend our example with two more objects, like so:

  var data = [{
    "name" : "Joe Bloggs",
    "age"  : "19",
    "from" : "United Kingdom"
  }, {
    "name" : "Jane Doe",
    "age"  : "21",
    "from" : "United State"
  }, {
    "name" : "John Doe",
    "age"  : "20",
    "from" : "United Nation"
  }];

Since we now have more than one object, our current template will no longer work to render these data correctly. In this case, we must use the Handlebars loop, wrapping our template within {{#each}} ... {{/each}}. We may also need to change the template structure.

In this example, we will display these data in a list.

  <script id="template" type="text/x-handlebars-template">
    <ul>
      {{#each this}}
        <li>Hi, My name is {{{name}}}. {{#if age}}I'm {{age}},{{/if}} and I'm from {{from}}</li>
      {{/each}}
    </ul>
  </script>

Here is the result that we will see in the browser:

Handlebars loop helper output

Example

Now let’s implement this in a real example. This time, we want to display a profile from Forrst, a hub for designers and developers. Forrst provides a simple method to retrieve data. In our case, we can use https://forrst.com/api/v2/users/info?username={username} to retrieve a user profile. We will get data similar to this (Note: the actual data is very long, so I have truncated it):

  var forrstProfile = {
    "id": 24606,
    "username": "jimmyliu",
    "name": "Jimmy Liu",
    "url": "http:\/\/forrst.com\/people\/jimmyliu",
    "likes": "11",
    "followers": "10",
    "following": "2",
    "photos": {
      "medium_url": "https:\/\/secure.gravatar.com\/avatar\/3151a9294608c3143551aa265f00bf71.jpg?s=75&d=https:\/\/forrst.com\/assets\/images\/default_75.jpg",
      "small_url": "https:\/\/secure.gravatar.com\/avatar\/3151a9294608c3143551aa265f00bf71.jpg?s=45&d=https:\/\/forrst.com\/assets\/images\/default_45.jpg",
      "thumb_url": "https:\/\/secure.gravatar.com\/avatar\/3151a9294608c3143551aa265f00bf71.jpg?s=25&d=https:\/\/forrst.com\/assets\/images\/default_25.jpg"
    },
    "bio": "<p>A graphic and web designer based in Cupertino, California. Follow me on Twitter <a href=\"http:\/\/twitter.com\/jimmyliu\"><\/a><a href=\"\/people\/jimmyliu\">@jimmyliu<\/a><\/p>\\n",
    "is_a": "developer & designer"
  };

We will put this data into the following template:

  <div id="forrst" class="forrst-profile">
    <script id="forrst-profile-template" type="text/x-handlebars-template">
      <div class="profile">
        <figure class="avatar">
          <img src="{{photos.medium_url}}" alt="">
        </figure>
        <div class="person">
          <h4 class="person-name"><a href="{{url}}">{{name}}</a></h4>
          <div class="person-bio">{{{bio}}}</div>
        </div>
      </div>
      <div class="social-count">
        <div class="social-item social-posts">
          <div class="heading">Posts</div>
          <div class="counts">{{posts}}</div>
        </div>
        <div class="social-item social-followers">
          <div class="heading">Followers</div>
          <div class="counts">{{followers}}</div>
        </div>
        <div class="social-item social-following">
          <div class="heading">Following</div>
          <div class="counts">{{following}}</div>
        </div>
      </div>
    </script>
  </div>

Let’s compile them together, like so:

  var template = $('#forrst-profile-template').html();
  var compile  = Handlebars.compile(template);
  var result   = compile(forrstProfile);
  $('#forrst').html(result);

With a couple of lines of CSS, we can achieve a nicer result.

You can download the source and see the demo from these links:

Final Thought

I previously used jQuery for templating, which I think was the wrong approach, as my code turned out messy. When dealing with a large chunk of data, it is far better and neater to use Handlebars for templating and displaying it. I hope this serves as a good reference for you to get started with Handlebars.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail