handlebars-helpers icon indicating copy to clipboard operation
handlebars-helpers copied to clipboard

forEach does not work with string arrays

Open Billydubb opened this issue 7 years ago • 2 comments

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

Billydubb avatar Jan 29 '18 20:01 Billydubb

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

foundy avatar Jan 30 '18 07:01 foundy

Thanks, I didn't know about the eachIndex helper

Billydubb avatar Jan 31 '18 09:01 Billydubb