1

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!

L-Ray
  • 1,637
  • 1
  • 16
  • 29

1 Answers1

1

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>
Patsy Issa
  • 11,113
  • 4
  • 55
  • 74
  • Hi @Kitler, thanks for that fast response. To make your example work, just the parameter in the html element have to be changed to ``valid`` and ``invalid`` instead ``active`` and ``inactive`` - and it runs like a charme. Thanks. Was hoping for an included version in HTMLBars, as this seems to be a common use case. – L-Ray Sep 04 '15 at 09:31
  • Oups, nice spot started off writing the helper with options to pass other operands missed it x.x – Patsy Issa Sep 04 '15 at 10:08
  • 1
    @L-Ray It is indeed common but it can be dealt with in many ways, another one is components for items and have it handle the logic of setting the class, we also have the ability to make our own custom helpers. – Patsy Issa Sep 04 '15 at 10:26
  • Handling it as part of the component is another great way to do it. I just figured out, that of course you can access variables given as parameters within the component via ``this.get('parameterName')``. Ahh, Ember can be great, sometimes... – L-Ray Sep 04 '15 at 14:12