JavaScript Templates with Handlebars.js
Templates are a very important part of modern day web applications written in JavaScript. Templating essentially encompasses the visual UI (user interface) components of these applications by rendering different “views” depending on the current state of the application. A “view” can be thought of as a certain type of layout. For example, when you sign in to an application and go to your account settings, you might be looking at a “profile” view. Or, if you were using an e-commerce application and you were browsing the site’s inventory, you might be looking at a “products” view. These views are dynamic in nature because they receive data that gets sent to them and then they render that data out in a manner that is meaningful and useful to the user.
There are many different templating libraries that can be used to render views in a JavaScript web application. No one library is necessarily better than another and it is likely that they all have their various strengths and weaknesses. We have looked at a couple of ways to do templates in Backbone.js applications and we’ll revisit one of the libraries used there: Handlebars.js. Handlebars is one of the templating libraries that I like very much for it’s simplicity and intuitive syntax. The Handlebars.js homepage has some very clear straightforward examples that allow you to jump right in to learning how to use it.
Handlebars template setups will look something like the following…
<!DOCTYPE html>
<html>
<head>
<title>Handlebars</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/handlebars.js" type="text/javascript"></script>
</head>
<body>
<div class="content"></div>
<script id="artist-list-template" type="text/x-handlebars-template">
<h1>{{ title }}</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Hometown</th>
<th>Favorite Color</th>
</tr>
</thead>
<tbody>
{{#each artists}}
<tr>
<td>{{ name }}</td>
<td>{{ hometown }}</td>
<td>{{ favoriteColor }}</td>
</tr>
{{/each}}
</tbody>
</table>
</script>
</script>
<script type="text/javascript">
var data = {
title: 'Artist Table',
artists: [
{ id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' },
{ id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' },
{ id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' }
]
}
var source = jQuery('#artist-list-template').html();
var template = Handlebars.compile(source);
var html = template(data);
jQuery('.content').html(html);
</script>
</body>
</html>
What we are doing here is passing data (in this case the JSON object in our data into) our artist list template (the one with id: #artist-list-template). Note that with our array or artists inside the {{ #each artists }} block (where we are looping over an array of JSON objects) the context has changed so we can directly refer to the artist name, hometown, and favoriteColor properties in for each item
In this example, we are using a static data object that we have created inline but in a real application it’s likely that you’d be getting that data via AJAX requests to APIs somewhere. But whether you get your data from a server or create it locally, the important part is that data can then be passed into the Handlebars template to be displayed by Handlebars. That is where using a templating engine becomes very efficient and very useful. The view/template does not need to worry about handing anything in the data. All of the code to handle getting data and then searching and sorting through it can be handled elsewhere. All your Handlebars template has to worry about is displaying the “final result” that your code generated elsewhere has produced.
There is also support for doing “multi-level” references of you have a JSON object that is x layers deep, you can refer to the properties inside it by normal dot syntax you might be familiar with.
<div class="entry">
<h1>{{title}}</h1>
<h2>By {{author.name}}</h2>
<div class="body">
{{body}}
</div>
</div>
<script type="text/javascript">
var data = {
title: "A Blog Post!",
author: {
id: 42,
name: "Joe Smith"
},
body: "This is the text of the blog post"
};
</script>
And there is even the possibility of doing conditionals via the built-in helper methods. For example, here is an if conditional in a Handlebars template where if a property does not exist or is null in an object that is passed to the view, a different “block” of code will be rendered.
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{else}}
<h1>Unknown Author</h1>
{{/if}}
</div>
And this is just scratching the surface. There are many other features and functionality that Handlebars.js provides. So head on over to the Handlebars.js homepage to start taking a look through the examples there to see what can be accomplished.
As we have seen Handlebars.js is very useful for creating a view layer in single-page JavaScript applications. Ember.js applications Handlebars.js by default, but you could certainly integrate Handlebars into applications built with other libraries. One of these examples is discussed here. But it should also be noted that there is also support for using Handlebars to render HTML on the server in a Node.js application before it is sent to the browser. For example, if you were building an Express.js application, you could use the express-handlebars module to handle the view component of your appplication by creating some dynamically generated HTML to server up to the browser. For more info on Node.js see this entry here, and for more info on building Express.js applications on top of Node.js see this entry here.
Hopefully you have found this discussion of Handlebars.js useful and that you consider using it for your templating needs in your next application. Download the files below to play around with this useful library…
Download Files



