【问题标题】:Where should non-template specific helpers be located in Meteor?非模板特定助手应该位于 Meteor 中的什么位置?
【发布时间】:2016-01-16 07:12:39
【问题描述】:

我有两个带表格的模板

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

和

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

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

如果我将两个表都放在同一个模板中,那么为模板创建帮助程序会很容易:

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

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

【问题讨论】:

    标签: javascript node.js templates meteor


    【解决方案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>
    

    选项二:

    如果你想用相同的内容填充表格,你可以将父模板的上下文传递给子模板以获取数据,如果你想要{{&gt; 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 
      });
    

    【讨论】:

    • 谢谢。但是该变量不应该是全局可访问的。这是一个集合选择器,这两个表几乎相同,所以我想我应该在助手之外定义选择器,这样我就可以为两个模板重用助手中的逻辑。
    • 好的,在同一个 js 文件中的两个模板中注册助手,我更新了我的答案。
    猜你喜欢
    • 2015-04-15
    • 2015-12-17
    • 2015-03-11
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多