February 28, 2021
Hot Topics:

Introducing JavaScript Templating with Handlebars.js

  • By Jason Gilmore
  • Send Email »
  • More Articles »

Few languages have had as wild a career as JavaScript. The John Travolta of programming languages, the trajectory of JavaScript's rocket to stardom was met with an equally bruising fall to earth before again suddenly establishing itself as an A-lister. These days everybody wants a piece of the language, and it seems to be playing a starring role across the Web.

JavaScript's elevated status can largely be attributed to the Web's migration away from traditional websites in preference of Web applications which mimic the interfaces and behavior of their desktop-bound brethren. Such applications tend to rely heavily on client-side JavaScript to produce highly responsive interfaces using a blend of complex layouts and Ajax. This paradigm presents a host of new problems to the developer, one of which pertains to the proper formatting of data returned from the server to JavaScript by way of an Ajax request. While it's possible to inject the data into HTML elements using a server-side language, this approach can be strikingly clumsy for even mildly complex projects.

Developers have remedied this problem by creating JavaScript-based solutions which can deftly inject data stored in a JavaScript object into a template. One particularly popular solution is Handlebars.js. In this article I'll show you how to start using Handlebars.js in conjunction to create highly manageable interfaces.

Installing Handlebars.js

To install Handlebars.js, either download it from GitHub or better, clone it:

$ git clone git://github.com/wycats/handlebars.js.git

Once downloaded, move the contents of the lib directory into a convenient location within your project directory structure, and reference handlebars.js within your page template:

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

Creating a Handlebars.js Template

The Handlebars.js template syntax resembles that used by many templating solutions, using brackets to delimit the dynamic data placeholders. For instance, consider a project which involved creating an online trainer for learning Morse code. To insert two variables named letter and code into a Handlebars.js template, you would identify them like this:

{{letter}} - {{code}}

Typically you'll pass dynamic data around in JavaScript using an object, meaning the letter and associated code might be stored like this:

var data = { alphabet: {
  letter: "A",
  code: ".-"

Alternatively, you might like to render an array of objects in order to for instance create a complete alphabetical chart of the letters and their Morse code equivalents:

var data = { alphabet: [
    {letter: "A", code: ".-"},
    {letter: "B", code: "-..."},
    {letter: "C", code: "-.-."},
    {letter: "D", code: "-.."},
    {letter: "E", code: "."}

In either case you can use the same template in conjunction with a Handlebars.js Block to render the results. Let's start with the template:

<script id="alphabet" type="text/x-handlebars-template" target="_blank">

By embedding the template within a script element assigned the type text/x-handlebars-template, the template will automatically be hidden from the page until called upon by Handlebars.js. Within this template you'll see the letter and code variables, both of which are embedded within a block named alphabet (the block opener is identified by the hashmark prefix).

Finally you'll define the Handlebars.js code used to render the template (in this example I'm using jQuery to facilitate various JavaScript-related tasks):

$(document).ready(function() {

  var data = { 
    alphabet: [
      {letter: "A", code: ".-" },
      {letter: "B", code: "-..." },
      {letter: "C", code: "-.-." },
      {letter: "D", code: "-.." },
      {letter: "E", code: "." }

  var layout   = $("#alphabet").html();
  var template = Handlebars.compile(layout);

The Handlebars.js-specific code really boils down to the last three lines. It begins by retrieving the template (identified by the alphabet DOM ID), and then compiles that layout into a JavaScript function (in the case of the above example, that function is named template). Finally, that function accepts the data as an argument, and the template output is displayed within an identified page element (in this case, a DIV assigned the ID chart).

Render this code within your browser and you'll see the data presented in a manner similar to that found in Figure 1 (I say similar because I used a bit of CSS to tweak the table):

Rendering a Handlebars.js Template
Figure 1. Rendering a Handlebars.js Template

Originally published on https://www.developer.com.

Page 1 of 2

This article was originally published on August 24, 2011

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date