简体   繁体   中英

Binding static and dynamic classes with HTMLBars

I'm trying to bind a static class 'form-control' and a dynamic property value 'color' to the class attribute of an input helper, however, the syntax I'm using just outputs this to the rendered DOM element

class="form-control {{color}}" 

without actually binding the value of 'color' to the class attribute. I know that this is the way to bind static and dynamic classes in normal DOM elements with HTMLBars, but is there a different syntax for elements that use curly-braces?

The syntax I'm using:

{{input class="form-control {{color}}" value=property.value type="text"}}

The double curly braces syntax invoke a helper or path in handlebars. But from within a helper you cannot use them to invoke a sub expression. Instead you have to use parenthesis to invoke a sub expression. For instance:

Wrong

{{input value={{uppercase user.name}} }}

Correct

{{input value=(uppercase user.name) }}

Because handlebars does not permit to interpolate literal values with dynamic ones. You'll need to use some custom helper to achieve what you want. Ember 1.3.2 comes with a concat helper, so you can use it like this:

{{input class=(concat "form-control " color) value=property.value type="text"}}

Notice the space in the end of "form-control" class, this is needed because the concat helper doesn't add any separator in the moment.

If you're using an old version, you can create a join-params helper to handle this for you:

app/helpers/join-params.js

import Ember from 'ember';

export function joinParams(params) {
  return params.join(' ');
}

export default Ember.HTMLBars.makeBoundHelper(joinParams);

And then use it without appending the space in the end of "form-control" class

{{input class=(join-params "form-control" color) value=property.value type="text"}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM