How do you add the “each in” to work in handlebars

Asked By: Anonymous

Ember is migrating to a non-context switching #each helper. For a compatibility piece I need to do the same from raw handlebars.

However the trivial attempt fails

var f = Handlebars.compile("{{#each numbers}}{{this}}{{/each}}");
console.log(f({numbers: [1,2,3]}));
// works

var f2 = Handlebars.compile("{{#each number in numbers}}{{number}}{{/each}}");
console.log(f2({numbers: [1,2,3]}));
// fails

How do I get {{#each number in numbers}} to work in raw handlebars 2.0?


Added a bounty here, for a handlebars extension based off that gives us each.. in support. It is clear its not built into handlebars. It is also clear Ember is able to extend this.


Answered By: Anonymous

This shows how it can be done. But note that it requires the stringParams flag at compile time, which changes the way all helpers get called, so this will probably break all the other helpers unless you provide stringParams compatible versions of them.

Handlebars.registerHelper('each', function(localName,inKeyword,contextName,options){
  var list = this[contextName];
  var output = "";
  var innerContext = Object.create(this);
  for (var i=0; i<list.length; i++) {
    innerContext[localName] = list[i];
    output += options.fn(innerContext);
  return output;

 var f = Handlebars.compile("{{#each number in numbers}}{{number}}{{/each}}", {
  stringParams: true

console.log(f({numbers: [1,2,3]}));
techinplanet staff

techinplanet staff

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno