alt
alt

Reputation: 13907

Handlebars conditional class attributes

Using EmberJS/Handlebars, how can I add a class to an element, only if a condition is true?

<div {{#if isSearching}}class="foo"{{/if}}></div>

Like that, but less pseudocode and more reality.

Upvotes: 18

Views: 22174

Answers (3)

Adam Cooper
Adam Cooper

Reputation: 8677

{{bind-attr}} is deprecated. You can use the new much nicer bound attribute syntax in Ember 1.10 and above, like so:

<div class="{{if isSearching 'foo'}}"></div>    

Upvotes: 55

chopper
chopper

Reputation: 6709

That won't work, because the {{#if}} helper will create tags in your HTML. Do this instead:

<div {{bind-attr class="isSearching:foo"}}></div>

Upvotes: 7

Simon Cateau
Simon Cateau

Reputation: 651

You have to use the {{bind-attr}} helper with a boolean condition, you can read the guide about this.

In your case, if the isSearching property is in the controller, you can just do the following:

<div {{bind-attr class="isSearching:foo"}}></div>

You can see the whole code in this fiddle: http://jsfiddle.net/NQKvy/240/

Upvotes: 9

Related Questions