Handlebars.js: Use a partial like it was a normal, full template Handlebars.js: Use a partial like it was a normal, full template jquery jquery

Handlebars.js: Use a partial like it was a normal, full template


If your templates are precompiled, you can access your partials via Handlebars.partials['partial-name']() as well as call them from a template via the {{> partial}} helper.

This is nice because you can then write a utility function for rendering a template whether it be a full blown template or partial.

ex:

function elementFromTemplate(template, context) {    context = context || {};    var temp = document.createElement('div');    temp.innerHTML = templates[template] ? templates[template](context) : Handlebars.partials[template](context);    return temp.firstChild;}

myDiv.appendChild(elementFromTemplate('myPartial', context));

myDiv.appendChild(elementFromTemplate('a-whole-template'));

Hope this helps anyone else who wants to use Handlebars like I do.


It's easier to do it the other way around - to compile all your templates as normal templates, then make them available as partials:

Handlebars.partials = Handlebars.templates

This makes it possible to use your templates as usual, and as partials as well:

{{> normalTemplate}}


To render a partial from javascript you can use

Handlebars.partials["myPartial"]()