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 a number of new features. Handlebars is a handful templating tool particularly for displaying a data serial in a form of JSON, which is today is a common data-formatting form used in a web application API. 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 of this article. If this is something that 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 of your project. Link the file from the HTML documents. You can either add the link inside the head tag or before the <body>.

<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>

When it is done, we can start creating a template.

Basic Template

Let’s add our data: name, age, and where the person come 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 open API such as Twitter, Instagram, Flickr and Dribbble – though you’ll get greater lines of data than what we have shown above. Alternatively, you can try JSON Generator to generate some random data.

The Template

Once we’ve got the data on our hands, we can create the template to place these data. Let’s take a 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>

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 with ID in JavaScript technically is more straightforward and faster than using a class.

While each of the data is declared within double curly braces, {{...}}; this is also known as Handlebars expression.

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

Compiling

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

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

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

var compile = Handlebars.compile(template);

The most important thing from 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 in #content using the jQuery .html() method this way.

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

This will give us the following result in the Browsers.

HTML Escaping

Sometimes our data could contain HTML tags, for example:

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

By default, Handlebars will escape these tags. They will turn the tag into their entity, < will turn into< while > will turn into >. So we will get an unexpected result, as shown below, in the browsers.

To prevent Handlebars from converting the HTML tags to their entity character, and to just treat them as they are, we 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; the name is displayed in italics.

Conditional Helper

Handlebars supports conditional helper (or also known as conditional function). This feature is an exclusive addition to Handlebars, not available in Mustache. Conditional helper is useful to prevent data rendering if the data 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 this way. As the age value is not present, we will not display the line that says I'm {{age}},.

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

In the browsers, the above line will be rendered.

In addition, Handlebars will also grant the data as empty if the value is explicitly specified with: undefined or false.

Loop

Handlebars also supports Loop. As in the other programming language, it is used to iterate a series of objects. At this point 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"
}];

As we now have more than one object. Our current template will no longer work to render these data into the template. In this case, we must use Handlebars Loop, wrap our template within {{#each}} ... {{/each}}. We may also change the template if needed.

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 browsers.

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 their data. In our case, we can use https://forrst.com/api/v2/users/info?username={username} to retrieve a user profile. We will get something similar to this data below.

Note: the actual data is really long. So I have to strip some of them out to make it shorter.

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 those data in this 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 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. It think I was doing it wrong, as my codes turn out to look like a mess. When we have a big chunk of data, it is far better and neater to use Handlebars for templating and displaying them. So I hope this can be a good reference for you to get started with Handlebars.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail