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


#1

Hello! 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 …


#2

If your html structure allows it, you can use the new @index helper available within each


#3

You might want to call a helper from inside the #each loop.

in HTML file:

<template name="posts">
  {{#each posts}}
    <span>{{this.number}} iteration &#124;</span>{{#if isSecondPost this}}<b>data</b> &#124;{{/if}}
  {{/each}}
</template>

in CoffeeScript file:

Template.posts.helpers
  isSecondPost: (post) ->
    post.number is 2

#4

This is silly little hack, but it works:

myList.js

Template.myList.helpers({
p : 0,
theList: function(){
    p = 0;
    return MyList.find();
},
pos: function(){
    p++;
    return p;
}

});

Template:

{{#each theList}}
           {{name}}  {{pos}}
{{/each}}

#5

What happens when you delete or update docs? Or insert new ones? I assume p would go out of sync.


#6

No, it works, each time theList() is accessed, it resets p


#7

Depends what you mean by inserting data.

in 1.2 you can access {@index} in #each and react based on that.

But I am used to create helpers like firstThree which do [0…3] in coffeescript.
Or inside helpers use map and in case of index being something react some special way


#8

How about something like this:

{{#each post}}
  {{> post}}
  {{{data @index}}}
{{/each}}
Template.name.helpers({
  posts: function() {
    return Posts.find();
  },
  data: function(index) {
    var val = index%2;
    if (val == 0)
      return 'data';
  }
});