2015-10-17 22 views
1

我有兩個模板,表格非模板特定助手應該放在Meteor中?

<template name="table1"> 
    <table>...</table> 
</template> 

<template name="table2"> 
    <table>...</table> 
</template> 

我想填充相同的變量都模板,但仍然有他們在兩個不同的模板分離。

這將是很容易地創建一個幫手的模板,如果我在同一個模板有兩個表:

<template name="bothTables"> 
    <table>...</table> 
    <table>...</table> 
</template> 

我想我應該能爲模板的幫手,但有邏輯變量別的地方。我應該在哪裏找到具有創建我想要填充到兩個模板的變量值的函數的文件?

回答

1

選項之一:

定義可以從所有模板使用的輔助函數。 http://docs.meteor.com/#/full/template_registerhelper

實施例:

1)create a file in client/lib/helpers.js

2)helper.js

Template.registerHelper('globalHelper', function(id) { 
    if(Meteor.userId() === id) 
    return "Yes"; 
    else 
    return "No"; 
}); 

3)在您的模板:

<template name="table1"> 
    <table>{{globalHelper '123'}}</table> 
</template> 

<template name="table2"> 
    <table>{{globalHelper '123'}}</table> 
</template> 

選項二:

如果要填充相同內容的表格中,你可以通過父模板的子模板的上下文獲取數據,如果你想{{> tableContent _id }}

<template name="table1"> 
     <table>{{> tableContent }}</table> 
    </template> 
    <template name="table2"> 
     <table>{{> tableContent }}</table> 
    </template> 

    <template name="tableContent"> 
     {{#each listOfData}} 
     <tr> 
     <td> 
      {{name}} 
     </td> 
     </tr> 
     {{/each}} 
    </template> 
    tableContent.js => 
     Template.tableContent.helpers({ 
     listOfData: function() { 
      return X.find({_id: this._id}); 
     } 
}); 

選項三: 在兩個模板中註冊助手。

<template name="table1"> 
     <table>{{ listOfData }}</table> 
</template> 

<template name="table1"> 
     <table>{{ listOfData }}</table> 
</template> 

table1.js=> 
    var listOfData = function(){ 
    return ExampleColleciont.find(); 
    }; 
    Template.table1.helpers({ 
    listOfData : listOfData 
    }); 
    Template.table2.helpers({ 
    listOfData : listOfData 
    }); 
+0

謝謝。但變量不應該是全局訪問的。它是一個集合選擇器,這兩個表幾乎相同,所以我想我應該在助手的外面定義選擇器,這樣我可以在這兩個模板中使用助手中的邏輯。 – Jamgreen

+0

好吧註冊助手在兩個模板在同一個js文件中,我更新了我的答案。 – Marztres