How do I precompile partials for handlebars.js?

Still not sure about precompiling partials, but this is how to call one template from within another template with help from this question: Handlebars helper for template composition

// instead of {{> partialName}} use {{partial "templateName"}}
Handlebars.registerHelper('partial', function(templateName,context){
    return new Handlebars.SafeString(Handlebars.templates[templateName](this));
});

http://jsfiddle.net/EBt8R/


I found an even better method: precompile all your partials as templates, then right before you use them in your code, add this line:

Handlebars.partials = Handlebars.templates;

The improvements are 1) it's shorter and 2) it doesn't loose any custom helpers you might pass in when calling the parent template.


I am using HandleBars v3.0.3 and I have partial and not partial templates pre-compiled in one file.

This thread is little bit confusing so I am summarizing the working solution.

  • Don't use -p operator while pre-compiling.
  • Don't register partial template by Handlebars.registerPartial('myPartial', '{{name}}');
  • use Nathan's suggestion of mapping partial object to templates object by Handlebars.partials = Handlebars.templates;
  • Refer partial template by name {{> name}}

As mentioned here on GitHub, there has been a -p flag added to the Handlebars CLI.

So you can use handlebars my_partial.handlebars -p -f output.js