【问题标题】:Using a helper with arguments AS a helper argument in Spacebars使用带参数的助手作为空格键中的助手参数
【发布时间】:2015-09-03 15:54:06
【问题描述】:

所以我尝试使用帮助器作为空格键中另一个帮助器的参数。在下面的示例中,“getResultInfo”是一个帮助器,用于获取特定于传递的参数的数据,“formatResult”是一个帮助器,用于格式化其结果和其他帮助器的结果。

<template name="example">
    {{#each collectionResults}}
        Label: {{formatResult getResultInfo this._id 'text'}}
    {{/each}}
</template>

我遇到的问题是 Spacebars 认为“getResultInfo”的参数只是“formatResult”的第二个和第三个参数。我真的很想将助手的功能分开(即不必在“getResultInfo”和我拥有的所有其他助手的末尾格式化结果)。是否有任何替代语法或方法可以实现我想要实现的目标?

【问题讨论】:

    标签: meteor spacebars


    【解决方案1】:

    我认为您不能像以前那样在第二个助手上使用参数链接两个助手。后续参数仍将被解释为来自第一个助手的参数。

    我看到了解决这个问题的两种方法:

    1) 你可以去掉参数并使用each 提供的数据上下文。 each 将数据上下文绑定到 this 所以在 getResultInfo 你可以直接使用 this._id。但是您必须记住,每次使用此帮助程序时都需要此数据上下文。这给不依赖于数据上下文的“文本”参数带来了问题。

    2) 您可以创建一个与您的 getResultInfo 助手对应的函数,并直接在 formatResult 助手中使用它,如下所示:

    getResultHelper = function(id, text) {
      //do what you want
    };
    
    //bind the function to your getResultInfo (example with a global helper)
    Template.registerHelper('getResultInfo', getResultHelper);
    
    //use the function in your template helper
    Template.example.helpers({
      formatResult: function(format) {
        return getResultHelper(this._id, format);
      }
    });
    
    //and finally your template
    <template name="example">
      {{#each collectionResults}}
        Label: {{formatResult 'text'}}
      {{/each}}
    </template>
    

    【讨论】:

      【解决方案2】:

      仅供参考,这在 Meteor 1.2 中现在可以通过 Blaze 中的空格键子表达式实现。

      <template name="example">
          {{#each collectionResults}}
              Label: {{formatResult (getResultInfo this._id 'text')}}
          {{/each}}
      </template>
      

      【讨论】:

        猜你喜欢
        • 2015-10-10
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 2017-12-03
        • 2013-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多