非模板特定助手应该放在Meteor的什么位置?
我有两个模板和表格
<template name="table1"> <table>...</table> </template>
和
<template name="table2"> <table>...</table> </template>
我想要使用相同的variables填充两个模板,但仍然有两个不同的模板分隔。
如果我在同一个模板中有两个表格,那么为模板创build一个辅助函数将很容易:
<template name="bothTables"> <table>...</table> <table>...</table> </template>
我想我应该为这两个模板创build一个助手,但在其他地方有variables的逻辑。 我应该在哪里find与我想要填充到两个模板的variables值的函数的文件?
scheme一:
定义一个可以从所有模板中使用的帮助函数。 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 });