为什么设置流星模板数据上下文替换父数据上下文?

时间:2015-05-28 20:58:23

标签: html meteor spacebars

我想将参数传递给我在循环中调用的模板:

<template name="show_people">
    <div class="panel-body">
       {{#each people}}
           <div>
                {{>person }}
                {{>person doing="running up the hill"}}
           </div>
      {{/each}}
    </div>
</template>

<template name="person">
     <h3>{{name}} is {{doing}}</h3>
</template>

助手javascript:

Template.show_people.helpers({
    people: function() { return [{ name: 'Jack' },{ name: 'Jill' }]; }
});

添加&#39;做&#39;模板的参数似乎破坏了循环项的上下文。这就是我要回来的地方:

Jack is
is running up the hill
Jill is
is running up the hill

我希望person模板能够访问参数和上下文。如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

快速入侵:将名称参数传递给从父上下文复制的模板。

{{> person name=name doing="running up the hill"}}

答案 1 :(得分:0)

接受的答案可以解决您的问题,但不会解释您遇到问题的原因。如果您查看“模板包含”部分标题下的this article,您将找到原因。

基本上,就在{{#each people}}{{/each}}代码块的内部,任何包含的模板的数据上下文将是people集合中的列表项。对于前两个代码段,people的两个实例的两个数据上下文将是{name: "Jack"}{name: "Jill"},这就是您看到{{1}的原因并且为这两个模板实例打印出Jack is。数据上下文不包含Jill is参数。

当您以第二种方式(doing)引用person模板时,将重置该模板实例的数据上下文,并创建仅包含指定参数的全新数据上下文。对于{{> person doing='running up the hill'模板的两个实例,数据上下文都是person,这就是您看到{doing: "running up the hill"}被打印两次的原因。

正如您所看到的,数据上下文设置不是附加的,而是独占的。数据上下文是出现给定模板引用的代码块的父数据上下文,或者是由模板引用中定义的所有参数组成的重写数据上下文。接受的答案之所以有效,是因为您将两个数据上下文合并为一个被覆盖的数据上下文,以便在is running up the hill模板中使用。

相关问题