Thomas Ardal

Entrepreneur and founder of elmah.io

Handlebars.js versus Knockout

![knockout](https://thoknockout ![handlebars](https://thandlebarsI’m still at the GOTO conference and having a blast, despite still being a bit struck by the flu. I attended another presentation about node.js. The presenter also demoed ember.js, Grunt and Azure and it was sort of interesting. What caught my attention where not really the key subjects, but the template engine used in emberjs: Handlebars.js. I’ve been using Knockout heavily during the last couple of years and loved every minute of it. In the old days, Knockout utilized the jQuery template engine, which I never really liked. Luckily Knockout now bundles its own shiny template engine whooping everyones ass. I wanted to spend a little time comparing Handlebars.js to Knockout.

The Knockout example:

Nice and simple. For each comment in an array named comments, add a new h2 containing a link to the title and a div containing the comment body.

Pros:

  • No magic strings
  • HTML validates
  • Compact

Cons:

  • Not possible to set attributes without data-bind
  • Annoying use of attr binding to concatenate strings

Now for the Handlebars.js example:

Same story. Iterate through the comments and show the details.

Pros:

  • Possible to write template code directly in attributes
  • Nice string concatenation using variables

Cons:

  • Magic strings ({{#each comments}})
  • More lines

So what’s the best approach? Personally I really don’t like the magic strings spread around the Handlebars.js code. On the other hand having the possibility to output the variables where they should be displayed, compared to the data-bind approach in Knockout, really makes the code simpler. I’ll definitely stick with Knockout, but Handlebars.js sure has some nice features I would like to see adopted by Knockout.

Show Comments