假设我有一个这样的数组:
var values = [
Ember.Object.create({id: 1, name: 'One'}),
Ember.Object.create({id: 2, name: 'Two'}),
Ember.Object.create({id: 3, name: 'Three'})
];
我想创建一个链接到每个不同对象的句子。输出将生成如下内容:
{{link-to 'One' 'my-route' 1}}, {{link-to 'Two' 'my-route' 2}}, and {{link-to 'Three' 'my-route' 3}}
它将输出一个句子,其中每个单词都链接到不同的路径:
One, Two, and Three
有没有可能动态地这样做呢?如果我只是迭代数组(see example),我知道如何创建链接的动态列表:
{{#each item in values}}
<li>{{link-to item.name 'my-route' item.id}}</li>
{{/each}}
但这并不能让我灵活地创建一个以'and‘结尾的逗号分隔的列表。
发布于 2014-10-25 04:04:49
我会创建一个计算属性来提供一些额外的信息。假设values
是控制器上的一个属性:
listValues: function() {
return this.get('values').map(function(item, index, array) {
return {
item: item,
isLastItem: index === array.length - 1
};
});
}.property('values.[]')
然后,在您的模板中:
{{#each listValues}}
{{#if isLastItem}}
and <li>{{link-to item 'my-route' item.id}}</li>
{{else}}
{{! Notice the trailing comma }}
<li>{{link-to item 'my-route' item.id}}</li>,
{{/if}}
{{/each}}
发布于 2014-10-25 04:16:51
这有点麻烦,但您可以创建一个计算属性,该属性包含除最后一项之外的所有项,并创建另一个计算属性来返回最后一项。
然后,在代码中对除最后一项之外的所有项进行#,然后执行and {{lastItem}}
。例如:
{{#each item in allButLast}}
{{link-to item.name 'test' item.id}},
{{/each}}
and {{link-to lastItem.name 'test' lastItem.id}}
下面是一个jsbin示例。
https://stackoverflow.com/questions/26554405
复制相似问题