【问题标题】:Handlebars, how to set a condition for a value returned by a helperHandlebars,如何为助手返回的值设置条件
【发布时间】:2013-10-09 15:33:34
【问题描述】:

我正在使用车把助手来计算数组中有多少行。如果它高于 2,则返回 true,并且可以按预期工作。看起来像这样:

define('templates/helpers/countRows', ['handlebars'], function ( Handlebars ) {
    function countRows(selectedArray) {
        var selectedArrayLength = selectedArray.length;
        if (parseInt(selectedArrayLength) > 2) {
            return true;
        }
    }
    Handlebars.registerHelper('countRows', countRows);
    return countRows;
});

问题是我想在我的 hbs 模板中设置一个条件,以在输出之前检查该值是否为真。如果不是真的,我不希望它输出。我希望我能做这样的事情:

{{#if countRows "my array"}}
    markup that only gets displayed if value is true
{{/if}}

但不幸的是,这无效..

【问题讨论】:

    标签: javascript jquery templates ember.js handlebars.js


    【解决方案1】:

    最好的方法是在控制器上定义计算属性来处理这种类型的逻辑。

    App.ThingsController = Ember.ArrayController.extend({
      enoughRows: Ember.computed.gte('content.length', 2)
    });
    

    然后在你的模板中:

    {{#if enoughRows}}
      ...
    {{/if}}
    

    在模板中嵌入这样的逻辑很难调试和测试。遵循这一理念,车把很难在真/假之外进行条件检查。

    如果您需要在许多控制器中重复这种逻辑,请考虑制作一个 mixin。

    App.EnoughRowsMixin = Ember.Mixin.create({
      enoughRows: Ember.computed.gte('content.length', 2)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2020-02-12
      相关资源
      最近更新 更多