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

后端 未结 8 1435
旧巷少年郎
旧巷少年郎 2020-12-04 15:40

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

相关标签:
8条回答
  • 2020-12-04 15:58

    To get specifically the parent of the partial (where you may be several partials deep) then follow the other answers like SeanWM.

    If you know that the parent is the main template then you can use @root which resolves to the top-most context no matter how deep you are.

    e.g. {{@root.rootObject.rootProperty}}

    It is a pity that ../../.. does not go up past a partial.

    0 讨论(0)
  • 2020-12-04 16:05

    Working fiddle (inspired by handlebars pull request #385 by AndrewHenderson) http://jsfiddle.net/QV9em/4/

    Handlebars.registerHelper('include', function(options) {
        var context = {},
            mergeContext = function(obj) {
                for(var k in obj)context[k]=obj[k];
            };
        mergeContext(this);
        mergeContext(options.hash);
        return options.fn(context);
    });
    

    Here's how you'd setup the parent template:

    {{#each items}} 
        {{#include parent=..}}
            {{> item-template}}
        {{/include}}
    {{/each}}
    

    And the partial:

    value is {{parent}}
    
    0 讨论(0)
提交回复
热议问题