Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put conditional class name inside helper

How to put conditional class name inside helper /component element?

like this: i have {{input}} if certain condition is fulfilled it classname should be changed, i can do that with if outside,

is there anyway to make this one liner?

{{#if model.bar.errors.name.length > 0}}
   {{input value=model.bar.name label='Bar Name' placeholder='The Name of Your Establishment' class=(model.bar.errors.name.length > 0 "color-" "blue")}}
{{#else}}
   {{input value=model.bar.name label='Bar Name' placeholder='The Name of Your Establishment' class="field-error"}}
{{/if}}
like image 481
DeckyFx Avatar asked Dec 18 '22 23:12

DeckyFx


1 Answers

The relevant concept in Ember is class name bindings.

There various ways to handle binding the name of a class or other html attribute to a value in your application:

1) inline if statement in the template:

<div class="{{if someVariable 'color-blue' 'not-color-blue}}">...</div>

2) passing in the classNameBindings attribute to your component:

// htmlbars template
{{foo-bar  classNameBindings="isBlue:color-blue" model=model}}

//component.js
isBlue: Ember.computed(function(){
  return (this.get('model.color.name') === 'blue');
})  

3) within your component.js (this is a good way to set default class bindings for an component—-when used in conjunction with #2 above, the class binding in the template will override the one in the component.js file):

//component.js
classNameBindings: ["isBlue:color-blue"],
isBlue: Ember.computed(function(){
  return (this.get('model.color.name') === 'blue');
}) 

Options #2 and #3 are the sanest approach. Notice classNameBindings is an array. You can specify an arbitrary number of bindings for an element with this syntax.

Documentation:
http://guides.emberjs.com/v2.0.0/components/customizing-a-components-element/

like image 111
Christopher Milne Avatar answered Dec 27 '22 15:12

Christopher Milne