Why Handlebars?

written by Tom Dale

UPDATE:

The following post refers to SproutCore 2.0, which has split off as a separate project. However, the information within this post is entirely applicable with respect to using SC.TemplateView and Handlebars in SproutCore 1.8. If you wish to use SC.TemplateView in SproutCore, you only need be aware that the many views and controls in the Desktop framework may contain templates, but should not themselves be contained within templates.


When people check out SproutCore 2.0 for the first time, one question that they frequently ask is: Do I have to use Handlebars?

Handlebars, if you’re not familiar with it, is a semantic templating language written entirely in JavaScript. It’s an expressive language with a tag syntax reminiscent of HTML, except expressions (oftentimes referred to as “mustaches”) are wrapped in double-curly braces. A simple template might look like this:

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

Handlebars, unlike other templating solutions like Eco, doesn’t tempt you to embed domain logic in your HTML. Anything other than simple conditionals and loops must be contained in your application’s JavaScript, which enforces the separation of concerns and leads to better testability. The language is also extensible with custom helpers, which allows you to effectively write a template DSL for your particular application.

So, while the answer to the question is use whatever templating system you’d like, we think Handlebars is a great option. Perhaps most importantly, we’ve spent a lot of time deeply integrating SproutCore and Handlebars, such that you get a lot for free just by using bindings, computed properties, and the SproutCore object system. In fact, while we like the features and simple-yet-expressive syntax of Handlebars, the real reason we chose it when creating SproutCore 2.0 was because of its speed and architecture, allowing us the kind of integration that would be very difficult with other templating libraries.
Continue reading