Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access previous element in {{#each }} loop

I'm wondering how to access previous element in {{#each items}} loop. For example Template.index.messages returns array of objects with name and message:

{{#each messages}}
  {{#if previousMessage.name != this.name }}
    {{name}}
  {{/if}}
  {{this.message}} 
{{/each}}

Basically I would like to hide name in consecutive messages. I made a workaround by filtering the messages in Template.index.messages, but that method is called every time data changes and therefore costs a lot of resources. So, how to do it in spacebars?

Thanks in advance.

like image 344
kikovi Avatar asked Jul 31 '26 10:07

kikovi


1 Answers

You can use https://github.com/raix/Meteor-handlebar-helpers when they accept my pull request https://github.com/raix/Meteor-handlebar-helpers/pull/65

otherwise you can add this to your project helpers to simulate the $mapped behaviour

UI.registerHelper("$mapped", function(arr, extended) {
    var extended = extended || false;
    if(!Array.isArray(arr)){
      try {
        arr = arr.fetch()
      }
      catch (e){
        console.log("Error in $mapped: perhaps you aren't sending in a collection or array.")
        return [];
      }
    }

    var $length = arr.length;

    var mappedArray = arr.map(function(item,index) {
      var newItem = _.clone(item);
      newItem.$length = $length;
      newItem.$index = index;
      newItem.$first = index === 0;
      newItem.$last  = index === $length-1;
      newItem.$index = index;
      if (extended) {
        newItem.$nextEl = arr[index+1];
        newItem.$prevEl = arr[index-1];
        newItem.$firstEl = arr[0];
        newItem.$lastEl = arr[$length-1];
      }
      return newItem;
    });

    return mappedArray || [];
});

Usage

{{#each $mapped yourCursor true}}
//Getting the next & previous element 
{{$nextEl._id}}
{{$prevEl._id}}
{{/each}}
like image 110
ghaliano Avatar answered Aug 04 '26 10:08

ghaliano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!