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 ?
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 ?
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
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.
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}}
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'}}
instead of using 'OR' try '||'. Or define a method in a javascript file.