把手 - 是否可以在部分中访问父上下文?

Ben*_*Ben 58 javascript templates handlebars.js

我有一个车把模板,为一个子元素加载一个部分.

我需要从部分中的调用模板中的父上下文中访问变量...似乎没有解决部分内部的任何问题.

简化的代码如下:

模板

    {{#each items}} 
        {{> item-template}}
    {{/each}}
Run Code Online (Sandbox Code Playgroud)

部分的

    value is {{value}}
Run Code Online (Sandbox Code Playgroud)

(显然真正的代码更复杂,但它是相同的原则,在部分内部..似乎是未定义的.)


为了表明它是未定义的,我使用了一个非常简单的帮手whatis:

Handlebars.registerHelper('whatis', function(param) {
    console.log(param);
});
Run Code Online (Sandbox Code Playgroud)

并将以上代码更新为:

更新的模板

    {{#each items}} 
        {{whatis ..}}  <-- Console shows the correct parent context
        {{> item-template}}
    {{/each}}
Run Code Online (Sandbox Code Playgroud)

更新部分

    {{whatis ..}}  <-- Console shows "undefined"
    value is {{value}}
Run Code Online (Sandbox Code Playgroud)

有办法解决这个问题吗?我错过了什么吗?

编辑:关于把手的github项目的这个问题有一个未解决的问题

Jam*_*res 39

以防万一有人偶然发现这个问题.此功能现在存在于Handlebars中.

做这个:

{{#each items}} 
    {{! Will pass the current item in items to your partial }}
    {{> item-template this}} 
{{/each}}
Run Code Online (Sandbox Code Playgroud)

  • 刚试过这个.不幸的是,Doenst为我工作.父上下文不会被传递."this"仅指项[[index],因此省略了父上下文.如果您传递".."(包括父上下文),则无法访问部分中的当前项. (16认同)
  • 您需要至少[版本2.0.0 alpha 1](http://cdnjs.com/libraries/handlebars.js/)才能使用此功能.另请查看[这些评论](https://github.com/wycats/handlebars.js/pull/182#issuecomment-32659931),因为它可能会有所不同. (3认同)
  • @Hans,你可以传递`{{> item-template parent = ..}}`然后在item-template中调用`{{parent.stuff}}`来访问每个外部的东西. (3认同)

小智 22

工作小提琴(灵感来自AndrewHenderson的车把拉动请求#385) 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);
});
Run Code Online (Sandbox Code Playgroud)

以下是您设置父模板的方法:

{{#each items}} 
    {{#include parent=..}}
        {{> item-template}}
    {{/include}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

部分:

value is {{parent}}
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这种方法,因为它的清洁度和灵活性相对于其他方法而言 (3认同)

Sea*_*nWM 10

2.0.0开始, partials现在支持传入值.

{{#each items}}
    {{> item-template some_parent_var=../some_parent_var}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

花了一些时间才发现这个,希望它对其他人也有用!


Ric*_*uza 3

您可以使用 github 链接中评论中提出的一些解决方案:

https://github.com/wycats/handlebars.js/issues/182#issuecomment-4206666
https://github.com/wycats/handlebars.js/issues/182#issuecomment-4445747

他们创建助手将信息传递给部分。