Search code examples
mongodbmeteorhandlebars.js

Looking at previous item in handlebars loop MeteorJS


I have a template in which I want to generate some HTML only if the current item has some different fields from the previous item.

{{#each item}}
  // if previous item.ar == current item.var, do X
  // else, do Y
{{/each}

How can I access the previous item?


Solution

  • You can transform your data via your helper. Here's an example using kittens... because everyone loves kittens right?

    Template.feline.helpers({
      kittens: function() {
        // fetch some kittens
        var kittens = Cats.find({_id: {$in: this.kittens}}).fetch();
    
        // keep track of the last kitten
        previousKitten = {};
    
        return _.map(kittens, function(kitten) {
          // add an isAwesome property based on the previous kitten
          if (previousKitten.eyeColor === kitten.eyeColor)
            kitten.isAwesome = true;
    
          previousKitten = kitten
          return kitten;
        });
      }
    });
    

    Now inside of the {{#each kittens}} iterator, you can test for the existence of isAwesome.