Using partials in SproutCore Handlebar views

Handlebars, like Mustache, support partials. And you can use this feature in a SproutCore app, but it takes a little bit of glue code.

We have established the convention that partial files have names that begin with an underscore, just as they do in Rails. We store them in resources/templates along with our other templates.

Add the following code to your app somewhere. We have it in a framework that holds a lot of our SproutCore extensions:

SC.ready(function() {
  SC.keys(SC.TEMPLATES).forEach(function(templateName) {
    var template = SC.TEMPLATES[templateName];

    if (template.rawTemplate && // we only want compiled templates
      templateName.substring(0,1) === '_') {
      Handlebars.registerPartial(templateName.replace('_', ''), template);
      delete SC.TEMPLATES[templateName];
    }
  });
});

Then, to render a partial in another template, use the standard syntax:

{{> partial_name }}

Don’t include the leading underscore in the partial name, and it should just work.