Loops 循环和数组,并添加除最后一个之外的分隔符
使用Handlebarjs,我想循环一个数组,并显示值,用分隔符分隔。如果我想显示的内容不是模板,那就很容易了;) 这是我的情况:Loops 循环和数组,并添加除最后一个之外的分隔符,loops,handlebars.js,Loops,Handlebars.js,使用Handlebarjs,我想循环一个数组,并显示值,用分隔符分隔。如果我想显示的内容不是模板,那就很容易了;) 这是我的情况: accounts = [ {'name': 'John', 'email': 'john@example.com'}, {'name': 'Malcolm', 'email': 'malcolm@example.com'}, {'name': 'David', 'email': 'david@example.com'} ]; {{#e
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}}
账户=[
{'name':'John','email':'john@example.com'},
{'name':'Malcolm','email':'malcolm@example.com'},
{'name':'David','email':'david@example.com'}
];
{{{#每个账户}
,
{{/每个}}
此实现的问题是,我将有以下输出:
约翰,马尔科姆,大卫
我希望它是:
约翰,马尔科姆,大卫
我如何做到这一点?我实现了一个新的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;
});
handlebar.registerHelper('foreach',函数(数组,fn){
var-total=array.length;
var缓冲区=“”;
//更好的性能:http://jsperf.com/for-vs-foreach/2
对于(变量i=0,j=total;i
然后:
{{#foreach accounts}}
<a href="mailto:{{ email }}" title="Send an email to {{ name }}">{{ name }}</a>{{#unless _isLast}}, {{/unless}}
{{/foreach}}
{{{#foreach accounts}
{{{除非{u isLast},{{/除非}
{{/foreach}}
我实现了一个新的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;
});
handlebar.registerHelper('foreach',函数(数组,fn){
var-total=array.length;
var缓冲区=“”;
//更好的性能:http://jsperf.com/for-vs-foreach/2
对于(变量i=0,j=total;i
然后:
{{#foreach accounts}}
<a href="mailto:{{ email }}" title="Send an email to {{ name }}">{{ name }}</a>{{#unless _isLast}}, {{/unless}}
{{/foreach}}
{{{#foreach accounts}
{{{除非{u isLast},{{/除非}
{{/foreach}}
您可以使用CSS伪类:after
,以及内容来实现所需的“格式化”。
(:在当前大多数浏览器和IE8+中的内容支持之后)
例如:
HTML:
结果:
Foo1, Foo2, Foo3
您可以使用CSS伪类:after
,与内容一起实现所需的“格式化”。
(:在当前大多数浏览器和IE8+中的内容支持之后)
例如:
HTML:
结果:
Foo1, Foo2, Foo3