Handlebars.js Part 3: Tips and Tricks

So we’re about done learning about Handlebars.js, but I’ve got a few examples of tricks I’ve found while using Handlebars that I figured I would share. If you haven’t read them yet, I’d highly recommend reading Part 1 and Part 2 of the series on Handlebars before you dive into this post.

The debug Helper

It can be easy at times to get confused about where you are in the stack in a Handlebars.js template. I usually keep a debug helper around to help me figure that out.

1
2
3
4
5
6
7
8
9
10
11
Handlebars.registerHelper("debug", function(optionalValue) {
  console.log("Current Context");
  console.log("====================");
  console.log(this);
 
  if (optionalValue) {
    console.log("Value");
    console.log("====================");
    console.log(optionalValue);
  }
});

You could then use that helper in any template like:

1
{{debug}}

or like:

1
{{debug someValue}}

and you’ll see output in the JavaScript console letting you know what’s going on:

1
2
3
4
5
6
7
8
9
10
11
12
Current Context
====================
email: "alan@test.com"
first_name: "Alan"
last_name: "Johnson"
member_since: "Mar 25, 2011"
phone: "1234567890"
stripeClass: "even"
__proto__: Object
Value
====================
Alan

A jQuery Plugin

It tends to be a pretty regular pattern with Handlebars to compile a template, process it with some data, and then fill a DOM element with the results. Here’s a quick jQuery plugin that does all of that for you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<html>
  <head>
    <title>What's Up?</title>
  </head>
  <body>
    <div id="content">
      This is where the content goes!
    </div>
    <script id="template" type="text/handlebars">
      Hello, {{name}}!
    </script>
    <script type="text/javascript" src="jquery.js"></script>
    <script src="handlebars-0.9.0.pre.5.js" type="text/javascript"></script>
    <script type="text/javascript">
      (function($) {
        var compiled = {};
        $.fn.handlebars = function(template, data) {
          if (template instanceof jQuery) {
            template = $(template).html();
          }
 
          compiled[template] = Handlebars.compile(template);
          this.html(compiled[template](data));
        };
      })(jQuery);
 
      $('#content').handlebars($('#template'), { name: "Alan" });
    </script>
  </body>
</html>

Updating More Than Just The Template Area

A lot of dynamic applications tend to have a layout that generally stays the same regardless of the template you’re displaying, and then a content area that shows the template that you’re looking at. Maybe there’s a sidebar with some navigation in it that generally stays the same, but each time you update the main content area you also need to update the title on the page. It’s pretty easy to cheat a bit with Handlebars to make that work. Handlebars helpers are allowed to not return anything, in which case they won’t add anything to the template output. You can use a helper that doesn’t return anything to update other parts of the page!

Imagine a site that has a structure something like this:

Sample App Layout

And maybe the markup looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
<body>
  <h1>Title</h1>
  <div id="nav-sidebar">
    <ul>
      <li>Links</li>
      <li>Go</li>
      <li>Here</li>
    </ul>
  </div>
  <div id="content">
  	Content goes here!
  </div>
</body>

Here’s a quick helper that will let you update the h1 for the title each time you apply content to the main content area:

1
2
3
4
5
Handlebars.registerHelper("title", function(fn) {
  $('h1').html(fn(this));
 
  return "";
});

And finally, a template that uses the helper:

1
2
3
4
5
  {{#title}}Details for {{name}}{{/title}}
 
  <div class="user-details">
    ...user details template stuff goes here...
  </div>

When the template above is run, it will call the title helper, but since the title helper just returns an empty string, it won’t add anything to the template output. It will, though, use jQuery to update the h1 element for the page’s title.

Wrapping Up

I think this about wraps up the series on Handlebars.js. It’s been fun to share Handlebars.js with everyone, and to hear about the apps you’re writing with Handlebars.js. Please let me know in the comments if there’s anything else relating to Handlebars.js that you’d be interested in hearing about, or if you have any questions.

Treehouse

Our mission is to bring affordable Technology education to people everywhere, in order to help them achieve their dreams and change the world.

Comments

12 comments on “Handlebars.js Part 3: Tips and Tricks

  1. Great timing with these articles! I just started toying with displaying Tumblr JSON via handlebars, but have run into troubles.

    Expressions with a dash in them don’t seem to work, like {{regular-title}} for example. Is this just a limitation with the handlebar/mustache expression?

    • Great question. The issue there is that Handlebars expects the expression to use valid JavaScript variable names. So anything with a dash wouldn’t be valid.

  2. In your jQuery plugin example, what are you accomplishing by using the ‘compiled’ object in ‘compiled[template] = Handlebars.compile(template);’? Why not just use a simple variable?

    I thought you might be attempting to cache the compiled template, but I don’t see a check against an existing cached item there.

  3. Handlebars updated meanwhile. Helpers now pass object with hash parameter if options is not defined. Upper debug helper always show value data in console although options parameter is not passed.

    To bypass this error, replace line #6 with:
    if (!optionalValue.hash && optionalValue) {

  4. When I first read the title of your post I thought the {{debug}} tag was going to do a JavaScript “debugger;” statement and I thought, how brilliant, I might create one and see if it helps debugging. I’ve created a Desktop application that allows you to run full handlebar templates on your desktop and was looking at debugging options, that’s how I found your article. You can see our reveal video here http://www.tiraggo.com/movies/M2G_Desktop_Reveal.html