流星:在子模板中使用变量

Meteor: Using variable in child template

本文关键字:变量 流星      更新时间:2023-09-26

我正在使用模板级订阅,但是在子模板中使用结果时遇到了一些问题:

当我加载模板example时,将显示模板exampleChild(仅将此作为基本示例 - 我知道现在没有意义(。

在创建主模板时,订阅已完成,数据存储在帮助程序中:

模板

<template name="example">
  {{> Template.dynamic template=switch}}
</template>
<template name="exampleChild">
  <h1>{{result}}</h1>
</template>

助手

Template.example.helpers({
  switch: function() { return 'exampleChild'; },
  result: function() { return Template.instance().result(); },
});

事件

Template.example.onCreated(function() {
  var instance = this;
  instance.autorun(function () {
      var subscription = instance.subscribe('posts');
  });
  instance.result = function() { 
    return Collection.findOne({ _id: Session.get('id') });
  }
});

如果我将{{result}}放在example模板中,一切正常。但是我需要在子模板中使用变量。

你试过吗:

<template name="example">
{{#with result}}
      {{> Template.dynamic template=switch}}
{{/with}}    
</template>
<template name="exampleChild">
  <h1>{{this}}</h1>
</template>

带文档

这样做时,我更喜欢将数据上下文结果包装到一个对象中,以便在子对象上有一些适当的内容,例如:

Template.example.helpers({
  switch: function() { return 'exampleChild'; },
  data: function() { return {result: Template.instance().result()} },
});
   <template name="example">
    {{#with data}}
          {{> Template.dynamic template=switch}}
    {{/with}}    
    </template>
    <template name="exampleChild">
      <h1>{{result}}</h1>
    </template>

希望有帮助

您可以将结果存储在会话变量中,然后将另一个帮助程序添加到等待会话变量的exampleChild