L-Ray
L-Ray

Reputation: 1647

Ember HTMLBars inline combined conditions

When trying to have a simple conditional style-class assignment in HTMLBars with Ember 1.13, the following code does a great job:

{{#each items as |item|}}
  <li class="tag {{if item.selected 'active' 'inactive'}}">{{item.key}}</li>
{{/each}}

Still, is there a way to combine conditions in the upper case, like checking for another condition? Something like the following code ...

{{#each items as |item|}}
  <li class="tag {{if (item.selected or noneSelected) 'active' 'inactive'}}">{{item.key}}</li>
{{/each}}

... or is the only way to achieve a check for several conditions via an Ember helper?

Thanks for your support!

Upvotes: 1

Views: 455

Answers (1)

Patsy Issa
Patsy Issa

Reputation: 11293

You will want to make your own helper let's call it conditional-or:

import Ember from 'ember';

const { Helper: { helper } } = Ember;

export function conditionalOr(conditions, {valid, invalid}) {
  invalid = invalid || '';
  return conditions.some(elem => elem) ? valid : invalid;
}

export default helper(conditionalOr);

What some() does is iterate over the array elements and return true when one meets the criteria.

And you will be able to use it in your template like so:

<li class="tag {{conditional-or item.selected noneSelected valid='active' invalid='inactive'}}">{{item.key}}</li>

Upvotes: 1

Related Questions