更新
从Polymer 1.2.0开始,您现在可以使用Compound Bindings来
在单个属性绑定或文本内容绑定中组合字符串文字和绑定
像这样:
<img src$="https://www.example.com/profiles/{{userId}}.jpg">
<span>Name: {{lastname}}, {{firstname}}</span>
和你的例子
<div class$="avatar {{color}}"></div>
所以这不再是一个问题。
以下答案现在仅与 1.2 之前的聚合物版本相关
如果您经常这样做,直到此功能可用,希望很快您可以在一个地方将该功能定义为Polymer.Base的属性,该属性具有所有聚合物元素继承的所有属性
//TODO remove this later then polymer has better template and binding features.
// make sure to find all instances of {{join( in polymer templates to fix them
Polymer.Base.join = function() { return [].join.call(arguments, '');}
然后这样称呼它:
<div class$="{{join('avatar', ' ', color)}}"></div>
然后当它被聚合物正确引入时,只需移除那一行,然后替换
{{join('avatar', color)}}
和
avatar {{color}}
我现在经常使用它,不仅用于将类组合成一个类,还用于路径名、使用“/”连接以及一般文本内容之类的东西,所以我使用第一个参数作为粘合剂。
Polymer.Base.join = function() {
var glue = arguments[0];
var strings = [].slice.call(arguments, 1);
return [].join.call(strings, glue);
}
或者如果你可以使用 es6 的特性,比如rest 参数
Polymer.base.join = (glue, ...strings) => strings.join(glue);
做类似的事情
<div class$="{{join(' ', 'avatar', color)}}"></div>
<img src="{{join('/', path, to, image.jpg)}}">
<span>{{join(' ', 'hi', name)}}</span>
只是基本的
Polymer.Base.join = (...args) => args.join('');
<div class$="{{join('avatar', ' ', color)}}"></div>