使用HTMLBars绑定静态和动态类 [英] Binding static and dynamic classes with HTMLBars
问题描述
我正在尝试将静态类form-control和动态属性值color绑定到输入帮助器的类属性,但是,我使用的语法只是将其输出到渲染的DOM元素
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}}"
没有将'color'的值实际绑定到类属性。我知道这是通过HTMLBars将普通DOM元素中的静态和动态类绑定的方式,但是使用花括号的元素有不同的语法吗?
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?
我使用的语法:
{{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:
错误
{{input value={{uppercase user.name}} }}
正确
{{input value=(uppercase user.name) }}
因为句柄不允许用动态值来插入字面值。您需要使用一些自定义帮助程序才能实现所需的功能。 Ember 1.3.2附带一个 concat
helper,所以你可以这样使用:
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"}}
注意form-control类的结尾处的空格,这是必需的,因为concat帮助程序暂时不添加任何分隔符。
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.
如果您使用的是旧版本,您可以创建一个 join-params
帮助程序来处理此问题:
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);
然后使用它,而不会在form-control类的末尾附加空格
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"}}
这篇关于使用HTMLBars绑定静态和动态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!