2013-09-24 27 views
2

所以,如果我有一個模板:Meteor.js:如何將一個助手的數據上下文傳遞給另一個助手?

<template name="myTemplate"> 
    {{foo}} 
</template> 

和模板幫手:

Template.myTemplate.foo = function() { 
    blah = Session.get('blah'); 
    // code to do stuff with blah 
    return blah; 
}; 

,然後我還有一個模板:

<template name="myOtherTemplate"> 
    {{foo}} 
</template> 

,我想這個數據上下文模板與之前的模板相同,我該怎麼做?

我首次想到,使用{{#with}}可能是正確的方法,但似乎只有在第二個模板的範圍已經在第一個範圍內時才起作用。

最終我希望能夠使用爲另一個模板中的一個模板定義的所有幫助程序,並知道如何執行此操作。

回答

3

好像你問的兩個問題之一:

  1. 如果您正在使用myOtherTemplatemyTemplate,其他模板的背景下將是相同的,因爲這一個,除非你明確地傳遞別的東西作爲部分的第二個參數。

    <template name="myTemplate"> 
        {{> myOtherTemplate foo}} 
    </template> 
    
  2. 如果您希望跨多個模板使用助手,請在全局助手中聲明它。這將使{{foo}}適用於所有模板:

    Handlebars.registerHelper("foo", function() { 
        blah = Session.get('blah'); 
        // code to do stuff with blah 
        return blah; 
    }); 
    
  3. 如果你想在運行自己的數據上下文(這是罕見的),請執行下列操作:

    <template name="myTemplate"> 
        {{{customRender}}} 
    </template> 
    
    Template.myTemplate.customRender = function() { 
        return Template.otherTemplate({ 
         foo: something, 
         bar: somethingElse, 
         foobar: Template.myTemplate.foo // Pass in the helper with a different name 
        }); 
    }; 
    

    這個對象基本上是Iron-Router將在渲染時傳遞給您的模板。 請注意,您將需要使用三把手{{{ }}}或使用new Handlebars.SafeString來告訴它不要轉義模板。

+0

你的答案是100%正確的,但我的措辭很差,它不是我正在尋找的東西。我不知道你是否使用過鐵路由器,但你可以做的其中一件事是通過數據傳遞數據上下文:...我想將主模板的數據上下文傳遞到頭模板。有沒有辦法將與單個模板關聯的所有幫助器都放到一個對象中並傳遞給它?也許數據:Template.myTemplate.helpers()或類似的東西。 (我會以任何方式給你答案,主要是好奇) – funkyeah

+0

數據上下文與模板助手不一樣。如果你想使用它們,你應該手動收集這些助手,因爲'Template.myTemplate'有一些附加在它上面的東西,你不想傳入。你可以把helper和data作爲一個對象傳入你希望,但要小心不要混淆自己。 –

相關問題