1

I've upgraded my meteor app to 0.8.0 and now the handlebars custom helpers have stopped working, the helper allows me to alter the behaviour when the last item is appended on to a list, does anyone know how I can get the handlebars helper working again or how I can get this functionality working with the latest version of meteor, thanks!

Helper Code (Original Link)

Handlebars.registerHelper("foreach", function(arr, options){

  if(options.inverse && !arr.length)
    return options.inverse(this);

  return arr.map(function(item, index){
    item.$index = index;
    item.$first = index === 0;
    item.$last  = index === arr.length - 1;
    return options.fn(item);
  }).join('');
});
Community
  • 1
  • 1
user1627990
  • 2,587
  • 2
  • 16
  • 18

3 Answers3

2

Meteor has migrated the Handlebars namespace to UI

UI.registerHelper("foreach", function(arr, options){
  return arr.map(function(item, index){
    item.$index = index;
    item.$first = index === 0;
    item.$last  = index === arr.length - 1;
    return options.fn(item);
  }).join('');
});
Pent
  • 1,049
  • 15
  • 17
  • Hey Pent! Thanks for the answer, I have a new problem now, I can't pass the array to the helper, {{#foreach foo}}{{/foreach}} and it's giving me the following error: "Exception from Deps recompute function: TypeError: Cannot read property 'inverse' of undefined" – user1627990 Apr 13 '14 at 15:00
  • Ah I see, I think it's more complex than I originally thought. An alternative thought: have you tried just modifying the list using jQuery? The Blaze engine is much more compatible with that – Pent Apr 13 '14 at 15:19
0

I've pretty much written my own helper function, it might not be the simplest solution before it works for me (for now!)

eachLastItem = function (arr){
  if(arr.length > 0){
    if(typeof arr[0] == "object"){
      var cnt = lastItem = 0;
      _.each(arr, function(obj){
        (cnt != arr.length - 1) ? lastItem = 0 : lastItem = 1;
        _.extend(arr[cnt], {__lastItem: lastItem});
        cnt++; });
    }else{
      var cnt = lastItem = 0;
      var newArr = [];
      _.each(arr, function(str){
        (cnt != arr.length - 1) ? lastItem = 0 : lastItem = 1;
          var newObj = {
            str: str,
            __lastItem: lastItem }
          newArr.push(newObj);
        cnt++;
      });
      arr = newArr;
    }
    return arr;
  }else{
    return null;
  }
}

and in the template, I use this:

{{#each array}}
  <li>{{str}}</li>
  {{#if __lastItem}}
    {{!  }}
  {{else}}
  {{/if}}
{{/each}}
user1627990
  • 2,587
  • 2
  • 16
  • 18
0

Make helper:

Template.registerHelper( 'isLastEach', ( arr, idx ) => {
    return arr.length == idx+1 ? true : false;
});

Use example using the built in @index helper:

{{#each yourArray}}             
    {{getNickname this}}{{#unless isLastEach yourArray @index }},{/unless}}
{{/each}}
Joe Berry
  • 26
  • 5