【问题标题】:Why Does Setting Meteor Template Data Context Replace Parent Data Context?为什么设置 Meteor 模板数据上下文会替换父数据上下文?
【发布时间】:2015-08-11 13:49:40
【问题描述】:

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

<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' }]; }
});

在模板中添加 'doing' 参数似乎破坏了循环项的上下文。这是我要返回的内容:

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

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

【问题讨论】:

    标签: html meteor spacebars


    【解决方案1】:

    快速破解:将 name 参数传递给从父上下文复制的模板。

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

    【讨论】:

      【解决方案2】:

      接受的答案解决了您的问题,但没有解释您遇到问题的原因。如果您查看 Template Includes 部分标题下的this article,您会找到原因。

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

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

      如您所见,数据上下文设置不是附加的,而是排他的。数据上下文要么是出现给定模板引用的代码块的父数据上下文,要么是由模板引用中定义的所有参数组成的覆盖数据上下文。接受的答案有效的原因是因为您将两个数据上下文组合到一个覆盖的数据上下文中,以便在 person 模板中使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-04
        • 2015-08-03
        • 2015-06-20
        • 2015-10-07
        • 2018-08-26
        • 1970-01-01
        • 2015-01-02
        • 2016-06-05
        相关资源
        最近更新 更多