Ember - 如果每个中有 lastItem
Ember - if lastItem in each
我试图在 ember 中的 each 中的最后一项下显示一段标记——我尝试了类似 @last 的东西——但返回时出现错误
<ul>
{{#each people as |person index|}}
<li>Hello, {{person.name}}! You're number {{index}} in line</li>
{{/each}}
</ul>
Ember 的 {{each}}
模板助手没有提供简单的方法。
正如您可能想到的,您可以使用 {{unless index}}
有条件地在第一个对象上渲染内容。这是有效的,因为索引从零开始并且 0
被认为是错误的。
您可以组合 ember-truth-helpers
and ember-math-helpers
来实现与最后一个元素相当的效果。两者都维护良好 ember 提供全套模板助手的插件。
Ember-truth-helpers 提供了一个 eq
帮助程序,它在模板中添加了对相等比较的支持。 Ember-math-helpers 提供了一个 sub
助手来从模板中的另一个值中减去一个值。将它们结合起来,我们可以构建一个仅对最后一个元素为真的条件:
{{#each items as |item index|}}
<li>
{{item}}
{{#unless index}}(first){{/unless}}
{{#if (eq index (sub items.length 1))}}(last){{/if}}
</li>
{{/each}}
您在此处找到了一个 ember 演示该方法的小游戏:https://ember-twiddle.com/6ea05a2e9c884bd772eefabc91173d08?openFiles=templates.application.hbs%2C
如果数组是 Ember.NativeArray
. NativeArray
of ember provides a lastObject
property,它会更简单,它指向数组中的最后一项。正如@Gaurav 在评论中指出的那样,您可以直接使用那个进行相等比较:{{#if (eq item items.lastObject)}}(last){{/if}}
但是请注意,如果数组具有重复的元素,这可能会给出错误的结果。
我试图在 ember 中的 each 中的最后一项下显示一段标记——我尝试了类似 @last 的东西——但返回时出现错误
<ul>
{{#each people as |person index|}}
<li>Hello, {{person.name}}! You're number {{index}} in line</li>
{{/each}}
</ul>
Ember 的 {{each}}
模板助手没有提供简单的方法。
正如您可能想到的,您可以使用 {{unless index}}
有条件地在第一个对象上渲染内容。这是有效的,因为索引从零开始并且 0
被认为是错误的。
您可以组合 ember-truth-helpers
and ember-math-helpers
来实现与最后一个元素相当的效果。两者都维护良好 ember 提供全套模板助手的插件。
Ember-truth-helpers 提供了一个 eq
帮助程序,它在模板中添加了对相等比较的支持。 Ember-math-helpers 提供了一个 sub
助手来从模板中的另一个值中减去一个值。将它们结合起来,我们可以构建一个仅对最后一个元素为真的条件:
{{#each items as |item index|}}
<li>
{{item}}
{{#unless index}}(first){{/unless}}
{{#if (eq index (sub items.length 1))}}(last){{/if}}
</li>
{{/each}}
您在此处找到了一个 ember 演示该方法的小游戏:https://ember-twiddle.com/6ea05a2e9c884bd772eefabc91173d08?openFiles=templates.application.hbs%2C
如果数组是 Ember.NativeArray
. NativeArray
of ember provides a lastObject
property,它会更简单,它指向数组中的最后一项。正如@Gaurav 在评论中指出的那样,您可以直接使用那个进行相等比较:{{#if (eq item items.lastObject)}}(last){{/if}}
但是请注意,如果数组具有重复的元素,这可能会给出错误的结果。