空格键:如何在 if 语句中使用和/或

spacebars: how to use and / or in if statements

我有以下代码:

 <div class="form-group {{#if afFieldIsInvalid name='latitude' OR name='longitude'}}has-error{{/if}}">......</div>

如何在空格键模板的 if 条件下使用 AND/OR?

Spacebars 是 Handlebars 的扩展,旨在成为一种无逻辑的模板语言。

解决方法是注册一个帮手。对于一般情况,请参阅以下类似问题:

  • How to do IF logic in HandleBars templates?

  • Include conditional logic in Handlebars templates, or just use javascript?

  • boolean logic within a handlebars template

要在 Meteor 中定义助手,请使用 Template.registerHelper

空格键无法处理逻辑表达式,因此您需要创建一个帮助程序来为您处理计算。

实际上,您可以通过这样的嵌套 ifs 实现 and 功能:

{{#if condition1}}
    {{#if condition2}}
        <p>Both condition hold!</p>
    {{/if}}
{{/if}}

or这样:

{{#if condition1}}
    <p>One of the conditions are true!</p>
{{else}}
    {{#if condition2}}
        <p>One of the conditions are true!</p>
    {{/if}}
{{/if}}

但我更愿意使用助手。

而不是使用 'OR' 试试'||'。 或者在 javascript 文件中定义一个方法。

您有专为这种情况设计的扩展程序。

Raix Handlebars

您可以使用这样的 'AND' 条件:

{{#if $in yourVariable 'case1' 'case2' }}
      Your code Here
{{/if}}

将解决方案更进一步。这将添加比较运算符。

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {

    switch (operator) {
        case '==':
            return (v1 == v2) ? options.fn(this) : options.inverse(this);
        case '===':
            return (v1 === v2) ? options.fn(this) : options.inverse(this);
        case '!=':
            return (v1 != v2) ? options.fn(this) : options.inverse(this);
        case '!==':
            return (v1 !== v2) ? options.fn(this) : options.inverse(this);
        case '<':
            return (v1 < v2) ? options.fn(this) : options.inverse(this);
        case '<=':
            return (v1 <= v2) ? options.fn(this) : options.inverse(this);
        case '>':
            return (v1 > v2) ? options.fn(this) : options.inverse(this);
        case '>=':
            return (v1 >= v2) ? options.fn(this) : options.inverse(this);
        case '&&':
            return (v1 && v2) ? options.fn(this) : options.inverse(this);
        case '||':
            return (v1 || v2) ? options.fn(this) : options.inverse(this);
        default:
            return options.inverse(this);
    }
});

在这样的模板中使用它:

{{#ifCond name='latitude' '||' name='longitude'}}

您可以使用 if-else 语法来做到这一点

<div class="form-group {{#if afFieldIsInvalid}} latitude {{else}} longitude {{/if}} has-error">...</div>