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

后端 未结 8 1461
旧巷少年郎
旧巷少年郎 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 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}}
    

提交回复
热议问题