车把条件 - 仅限布尔属性?

Handlebars conditionals - boolean properties only?

快速提问。是否可以在车把条件中评估布尔值 属性 以外的东西?

例如这行得通

//elsewhere...  myproperty = true
{{#if myproperty}}...

有什么办法可以完成其他条件吗?例如

//elsewhere...  myproperty = 3
{{#if myproperty<4}}...

不能在模板中做{{#if myproperty<4}}

请参阅以下问题,了解在这种情况下该怎么做的示例

How do I make a conditional helper with ember-cli and handlebars 2.0.0?

没有帮手,你不可能有if的评估条件。但是,你可以让一个助手来做这件事:

Handlebars.registerHelper('iff', function(left, condi, right, options) {
    function ret(bool) {
        if (bool) {
            return options.fn(this);
        } else {
            return options.inverse(this);   
        }
    }

    switch (condi) {
        case "==":
            ret(left == right);
        case "!=":
            ret(left != right);
        case ">":
            //etc, etc, you get the idea
        default:
            return options.inverse(this);
    }
});

用法:

{{#iff myproperty "<" 4}}
    Myproperty is less than 4
{{else}}
    Myproperty is greater than or equal to 4
{{/iff}}

--编辑--

Haven't tried this yet but it looks sensible and straightforward. Begs the question why Handlebars doesn't support more complex conditionals natively...

将逻辑与模板(视图)分开是一种很好的做法,因为这样可以使您的代码更易于维护。本质上,它遵循 separation of concerns 原则。

就我个人而言,我认为有条件的 if 也很有用,因为在模板中肯定有一次性 if 语句的位置,同时保持您的逻辑和视图分开。但是,默认情况下不包括它,它在某种程度上可以使用户免受自身伤害,因此您最终不会看到 20 多个嵌套的 if 语句。

最佳解决方案是使用 ember-truth-helpers

所以在你的情况下你会使用 {{if (lt myproperty 4)}}