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.

Handlebars.registerHelper("debug", function(optionalValue) {
  console.log("Current Context");

  if (optionalValue) {

You could then use that helper in any template like:


or like:

{{debug someValue}}

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

Current Context
email: ""
first_name: "Alan"
last_name: "Johnson"
member_since: "Mar 25, 2011"
phone: "1234567890"
stripeClass: "even"
__proto__: Object

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:

    What's Up?
This is where the content goes!

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:



Content goes here!

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:

Handlebars.registerHelper("title", function(fn) {

  return "";

And finally, a template that uses the helper:

  {{#title}}Details for {{name}}{{/title}}

...user details template stuff goes here...

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.