更新
从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 之前的聚合物版本相关
如果您经常这样做,直到此功能可用(希望是 soon),您可以在一个地方将该功能定义为 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);
}
或者如果你可以使用 rest arguments 等 es6 功能
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>