问题
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