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

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

问题描述



在我的Handlebars模板中:

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

  {{每个列表}} 
{{name}} {{status}},
{{/ each我想要不要显示在最后一项。有没有办法在Handlebars中做到这一点,还是需要回到CSS选择器?



更新:根据Christopher的建议,是我最终实现的:

  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 attachmentments}} 

和项目视图: p>

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


解决方案

您可以使用标准CSS来执行此操作:

  li:之后{
content:',';
}

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

我喜欢单独的规则,但更简洁如果稍微不太可读的版本(从@Jay在评论中):

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


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

In my Handlebars template:

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

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()
    })
}));

and in my view:

{{collection attachments}}

and the item view:

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

解决方案

You can use standard CSS to do this:

li:after {
    content: ',';
}

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

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天全站免登陆