Javascript – handlebars – is it possible to access parent context in a partial

handlebars.jsjavascripttemplates

I've got a handlebar template that loads a partial for a sub-element.

I would need to access a variable from the parent context in the calling template, from within the partial. .. doesn't seem to resolve to anything inside the partial.

Simplified code goes like this:

the template

    {{#each items}} 
        {{> item-template}}
    {{/each}}

the partial

    value is {{value}}

(obviously the real code is more complicated but it's the same principle, within the partial .. appears to be undefined.)


To show it's undefined, I've used a very simple helper whatis like this:

Handlebars.registerHelper('whatis', function(param) {
    console.log(param);
});

and updated the above code to this:

updated template

    {{#each items}} 
        {{whatis ..}}  <-- Console shows the correct parent context
        {{> item-template}}
    {{/each}}

updated partial

    {{whatis ..}}  <-- Console shows "undefined"
    value is {{value}}

Is there a way to go around that issue? Am I missing something?

EDIT: There's an open issue relating to this question on handlebars' github project

Best Answer

Just in case anyone stumbles across this question. This functionality exists now in Handlebars.

Do this:

{{#each items}} 
    {{! Will pass the current item in items to your partial }}
    {{> item-template this}} 
{{/each}}