If you tried Ember.js, you may have noticed that it is not possible to use logical operators in templates. For example, such template will not work:
{{#if (param1 || param2)}} Will not work {{/if}}
Instead, you supposed to combine param1
and param2
into a computed property (param3) in your controller (component, model) and use this computed property in your template:
import Ember from 'ember'; export default Ember.Controller.extend({ param3: Ember.computed('param1', 'param2', function () { return this.get('param1') || this.get('param2'); }) });
{{#if param3}} Will work {{/if}}
Quite a lot of coding for such simple task, isn’t it? Surely, this method helps to keep templates simple and it is good if you need such logic just in one-two places. But what if you need to combine conditions often? Or do it in {{#each}}
block? A helper will help.
First, create a file /path-to/app/helpers/logical-or.js
. You may run ember generate helper logical-or
to make ember-cli generate it for you. Put following lines in this file:
//..app/helpers/logical-or.js import Ember from 'ember'; export function logicalOr(params) { var result = false; for (var i = 0; i < params.length; i++) { result = result || !!params[i]; } return result; } export default Ember.Helper.helper(logicalOr);
Now you can use your new helper in any template:
{{#if (logical-or param1 param2)}} Will work {{/if}}
If you need, you may pass more than 2 parameters:
{{#if (logical-or param1 param2 param3 param4 param5)}} Will work {{/if}}
You may also create logical-and helper (as a replacement for &&) and even combine them in templates.
That’s all. Have a nice code!
Featured image source – pxhere.com