How to get index in Handlebars each helper?
I'm using Handlebars for templating in my project. Is there a way to get the index of the current iteration of an "each" helper in Handlebars?
<tbody>
{{#each item}}
<tr>
<td><!--HOW TO GET ARRAY INDEX HERE?--></td>
<td>{{this.key}}</td>
<td>{{this.value}}</td>
</tr>
{{/each}}
</tbody>
In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.
snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811
The index of the current array item has been available for some time now via @index:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
For object iteration, use @key instead:
{{#each object}}
{{@key}}: {{this}}
{{/each}}
This has changed in the newer versions of Ember.
For arrays:
{{#each array}}
{{_view.contentIndex}}: {{this}}
{{/each}}
It looks like the #each block no longer works on objects. My suggestion is to roll your own helper function for it.
Thanks for this tip.
I know this is too late. But i solved this issue with following Code:
Java Script:
Handlebars.registerHelper('eachData', function(context, options) {
var fn = options.fn, inverse = options.inverse, ctx;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ctx = Object.create(context[i]);
ctx.index = i;
ret = ret + fn(ctx);
}
} else {
ret = inverse(this);
}
return ret;
});
HTML:
{{#eachData items}}
{{index}} // You got here start with 0 index
{{/eachData}}
if you want start your index with 1 you should do following code:
Javascript:
Handlebars.registerHelper('eachData', function(context, options) {
var fn = options.fn, inverse = options.inverse, ctx;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ctx = Object.create(context[i]);
ctx.index = i;
ret = ret + fn(ctx);
}
} else {
ret = inverse(this);
}
return ret;
});
Handlebars.registerHelper("math", function(lvalue, operator, rvalue, options) {
lvalue = parseFloat(lvalue);
rvalue = parseFloat(rvalue);
return {
"+": lvalue + rvalue
}[operator];
});
HTML:
{{#eachData items}}
{{math index "+" 1}} // You got here start with 1 index
{{/eachData}}
Thanks.
链接地址: http://www.djcxy.com/p/61582.html上一篇: Ember.js中的把手助手