Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handlebars - is it possible to access parent context in a partial?

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

like image 434
Ben Avatar asked Feb 23 '12 10:02

Ben


1 Answers

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}} 
like image 152
James Andres Avatar answered Oct 19 '22 03:10

James Andres