非模板特定助手应该放在Meteor中的哪个位置?

时间:2015-10-17 16:39:20

标签: javascript node.js templates meteor

我有两个带表格的模板

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

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

我想用相同的变量填充两个模板,但仍然将它们分成两个不同的模板。

如果我在同一个模板中有两个表,那么为模板创建一个帮助器会很容易:

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

我想我应该为两个模板创建一个帮助器,但是在其他地方有变量的逻辑。我应该在哪里找到具有创建我想要填充到两个模板的变量值的函数的文件?

1 个答案:

答案 0 :(得分: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 
  });