Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...