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

handlebars.js, javascript, jquery, templates

Solution

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.

Problem

I have a template that I want to use both as a partial, and by itself from javascript.

Original source