Meteor - #each iteration of an array with another HTML element inserted after each nth item

喜你入骨 提交于 2019-12-02 14:28:04

问题


I'm iterating over an array of items in Meteor using Blaze using the #each iterator, and I want to insert an HTML element after each nth (10th) item. I figured I could use @index to access what index of the array I'm at, but don't really know how to insert another element every 10th element.

{{#each getArray}}
  <div class="item" data-value="{{someHelper @index}}">{{this}}</div>
{{/each}}

回答1:


Based on your comment, it seems like you'd want to make a custom helper that returns whether or not you should have an element in the DOM:

{{#each getArray}}
  <div class="item" data-value="{{someHelper @index}}">{{this}}</div>
  {{#if shouldAddDiv @index}}
    <div>I was after the 10th item!</div>
  {{/if}}
{{/each}}

Template.TemplateName.helpers({
  shouldAddDiv(index) {
    if(index % 10 === 0) {
      return true;
    } else {
      return false;
    }
  }
});

If you don't want the div to appear after the first element, you'd change the index % 10 to index % 9




回答2:


You can use modulo (%), which takes the remainder of two numbers. For example 11%3 = 2, because 3 fits 3 times in 11, leaving 2 aka the remainder.

Template.TemplateName.helpers({
    'someHelper': function(whichOne){
        if (whichOne%10 == 0){
            yourArray.push(<newElement>);
        }
    }
});

Whenever whichOne%10 is zero, you've hit the tenth element in your array.



来源:https://stackoverflow.com/questions/35832183/meteor-each-iteration-of-an-array-with-another-html-element-inserted-after-ea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!