Binding static and dynamic classes with HTMLBars

感情迁移 提交于 2019-12-12 12:06:23

问题


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"}}

回答1:


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"}}


来源:https://stackoverflow.com/questions/31101967/binding-static-and-dynamic-classes-with-htmlbars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!