【问题标题】:Meteor: Using variable in child templateMeteor:在子模板中使用变量
【发布时间】:2016-02-16 06:19:59
【问题描述】:

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

当我加载模板 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-模板中,一切正常。但是我需要在子模板中使用变量。

【问题讨论】:

  • 你让它看起来子模板不包含在父模板中,它们实际上是兄弟姐妹。请说明他们是否有兄弟姐妹或父母/子女关系。
  • 这是一个孩子,只是使用 Dynamic.template ,目前还不是很“常见”,可能会混淆@Eleant.Scripting

标签: javascript meteor


【解决方案1】:

你试过了吗:

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

<template name="exampleChild">
  <h1>{{this}}</h1>
</template>

With doc

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

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>

希望对你有帮助

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 2016-04-02
      • 2016-02-21
      • 2014-07-03
      • 2015-12-20
      • 2023-03-05
      相关资源
      最近更新 更多