spacebars: how to use and / or in if statements

无人久伴 提交于 2019-12-10 14:31:45

问题


I have following code:

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

How can I use AND/OR in if conditions of spacebars templates ?


回答1:


Spacebars is an extension of Handlebars, which is designed to be a logic-less template language.

The solution is to register a helper. For the general case, see these similar questions:

  • How to do IF logic in HandleBars templates?

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

  • boolean logic within a handlebars template

To define helpers in Meteor, use Template.registerHelper




回答2:


Spacebars can't handle logical expressions, so you need to create a helper handling the calculations for you.

Actually, you can achieve and functionality with nested ifs like this:

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

And or like this:

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

But I would prefer using a helper.




回答3:


You have an extension designed for this case.

Raix Handlebars

You can use for an 'AND' condition something like this:

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



回答4:


Taking the solution one step further. This adds the compare operator.

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);
    }
});

Use it in a template like this:

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



回答5:


instead of using 'OR' try '||'. Or define a method in a javascript file.



来源:https://stackoverflow.com/questions/28426843/spacebars-how-to-use-and-or-in-if-statements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!