循环遍历数组并添加除最后一个之外的分隔符

时间:2012-12-13 13:37:36

标签: loops handlebars.js

使用Handlebarjs,我想循环一个数组,并显示由分隔符分隔的值。如果我想要显示的内容也不是模板,那将很容易;)

这是我的情况:

accounts = [
     {'name': 'John', 'email': 'john@example.com'},
     {'name': 'Malcolm', 'email': 'malcolm@example.com'},
     {'name': 'David', 'email': 'david@example.com'}
];

{{#each accounts}}
    <a href="mailto:{{ email }}" title="Send an email to {{ name }}">{{ name }}</a>,
{{/each}}

这个实现的问题是我将有这个输出:

  

John,Malcolm,David,

我希望它是:

  

约翰,马尔科姆,大卫

我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以使用CSS伪类:after以及内容来实现所需的“格式化”。 (:after和今天大多数浏览器中的内容支持,以及IE8 +。)

例如:

HTML:

<a href="mailto:xxx@xxxx.com" title="Send an email to Foo">Foo1</a>
<a href="mailto:xxx@xxxx.com" title="Send an email to Foo">Foo2</a>
<a href="mailto:xxx@xxxx.com" title="Send an email to Foo">Foo3</a>

CSS:

a {
  color: red;
}
a:after {
  content: ", ";
}
a:last-child:after {
  content: "";
}

结果:

Foo1, Foo2, Foo3

答案 1 :(得分:2)

我实现了一个新的foreach助手,可以解决这个问题:

Handlebars.registerHelper('foreach', function (array, fn) {
    var total = array.length;
    var buffer = '';

    //Better performance: http://jsperf.com/for-vs-foreach/2
    for (var i = 0, j = total; i < j; i++) {
        var item = array[i];

        // stick an index property onto the item, starting with 1, may make configurable later
        item['_index'] = i+1;
        item['_total'] = total;
        item['_isFirst'] = (i === 0);
        item['_isLast'] = (i === (total - 1));

        // show the inside of the block
        buffer += fn.fn(item);
    }

    // return the finished buffer
    return buffer;
});

然后:

{{#foreach accounts}}
    <a href="mailto:{{ email }}" title="Send an email to {{ name }}">{{ name }}</a>{{#unless _isLast}}, {{/unless}}
{{/foreach}}