Search code examples
meteorspacebars

In Spacebars, how to enter data between iterations {{# each}}?


I'm using Spacebars and Meteor 1.2. In {{#each post}}, how to enter data after a specific iteration. For example after the second iteration.

Example: 1º iteration | 2º iteration | data | 3º iteration | 4º iteration ...


Solution

  • Firstly, convert your cursor to an array and add an index attribute. You're also going to need a helper to check equality (or to tell you when the conditions are right to display something different):

    Template.myTemplate.helpers({
      post: function(){
        var cursor = Posts.find({}); // whatever your query is   
        var array = _.map(cursor, function(doc, index) {
          doc.iteration = index + 1; // add an 'iteration' key starting at 1 instead of 0
          return doc;
        });
        return array;
      },
      equals: function(a,b){ // determine equality of a and b for use in spacebars
        return a==b;
      }
    });
    

    Then in your html template:

    <template name="myTemplate">
      {{#each post}}
        Title: {{title}}
        {{#if equals iteration 2}} Second iteration {{/if}}
      {{/each}}
    </template>