handlebars-helpers
handlebars-helpers copied to clipboard
forEach does not work with string arrays
Since strict mode is being used, the line
item.index = i + 1;
causes an error when array
is a string array such as ['hello', 'world']
.
helpers.forEach = function(array, options) {
var data = utils.createFrame(options, options.hash);
var len = array.length;
var buffer = '';
var i = -1;
while (++i < len) {
var item = array[i];
data.index = i;
item.index = i + 1;
item.total = len;
item.isFirst = i === 0;
item.isLast = i === (len - 1);
buffer += options.fn(item, {data: data});
}
return buffer;
};
forEach support object arrays. forEach
You can use the eachIndex
helper. eachIndex
{{#eachIndex array}}{{item}}{{/eachIndex}}
or just use the built-in each
helper.
{{#each array}}{{this}}{{/each}}
Thanks, I didn't know about the eachIndex
helper