gpt4 book ai didi

javascript - Handlebars,如何为助手返回的值设置条件

转载 作者:行者123 更新时间:2023-11-29 16:14:25 24 4
gpt4 key购买 nike

我正在使用 Handlebars 助手来计算数组中有多少行。如果它大于 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}}

但不幸的是,这是无效的..

最佳答案

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

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

然后在你的模板中:

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

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

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

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

关于javascript - Handlebars,如何为助手返回的值设置条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19276384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com