2016-02-15 88 views
0

我使用模板级订阅,但我有一些问题想使用一个子模板结果:流星:在子模板使用可变

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

+0

你让它看起来像子模板不包含在父te他们实际上是兄弟姐妹。请说明他们是否有兄弟姐妹关系或父母/子女关系。 –

+0

这不是小孩? – user3142695

+0

这是一个孩子,只是使用Dynamic.template,这个时候并不是很“常见”,可能会混淆@ Eleant.Scripting –

回答

0

你尝试:

<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> 

希望它的帮助

0

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