2016-02-15 32 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