除了最后一个元素之后,如何在 {{#each}} 循环中的元素之间添加分隔符? [英] How do I add a separator between elements in an {{#each}} loop except after the last element?

查看:26
本文介绍了除了最后一个元素之后,如何在 {{#each}} 循环中的元素之间添加分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Handlebars 模板,我正在尝试从数组中生成逗号分隔的项目列表.

I have a Handlebars template where I'm trying to generate a comma-separated list of items from an array.

在我的把手模板中:

{{#each list}}
    {{name}} {{status}},
{{/each}}

我希望 , 不出现在最后一个项目上.有没有办法在 Handlebars 中做到这一点,还是我需要回退到 CSS 选择器?

I want the , to not show up on the last item. Is there a way to do this in Handlebars or do I need to fall back to CSS selectors?

更新:根据克里斯托弗的建议,这是我最终实施的:

UPDATE: Based on Christopher's suggestion, this is what I ended up implementing:

var attachments = Ember.CollectionView.extend({
    content: [],
    itemViewClass: Ember.View.extend({
        templateName: 'attachments',
        tagName: 'span',
        isLastItem: function() {
            return this.getPath('parentView.content.lastObject') == this.get('content');
        }.property('parentView.content.lastObject').cacheable()
    })
}));

在我看来:

{{collection attachments}}

和项目视图:

{{content.title}} ({{content.size}}) {{#unless isLastItem}}, {{/unless}}

推荐答案

您可以使用标准 CSS 来做到这一点:

You can use standard CSS to do this:

li:after {
    content: ',';
}

li:last-of-type:after {
    content: '';
}

我更喜欢单独的规则,但更简洁但可读性稍差的版本(来自评论中的@Jay):

I prefer separate rules, but a more concise if slightly less readable version (from @Jay in the comments):

li:not(:last-of-type):after {
    content: ',';
}

这篇关于除了最后一个元素之后,如何在 {{#each}} 循环中的元素之间添加分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆