Spacebars rendering according to index

101 Views Asked by At

I need to open a row when the index modulus is 0 and close it when it is 1, something similar to this idea:

{{each posts}}
    {{#if @index%2==0}}
         <div class="row">
    {{/if}}
             <div class="col-lg-6">HELLO</div>
    {{#if @index%2==1}}
         </div>
    {{/if}}
{{/each}}

OF course that this code/idea doesn't compile. How can I achieve it?

UPDATE Sorry, maybe I didn't explain it well. What I want to do is something similar to this PHP code but using meteor. (changed some numbers for a better understanding).

for($i = 0; $i<count(array); $i++):
    if($i%4 == 0):
        echo '<div class="row">';
    endif;
        echo '<div class="col-lg-3">HELLO</div>';
    if($i%4==3 || $i == count(array) -1):
        echo '</div>';
    endif;
endfor;

I have one solution with a helper that returns a two dimensional array there is another way of doing it.

2

There are 2 best solutions below

0
On

If you wish to create the element in the middle no matter what, I would do something like this

{{#each posts}}
    <div class="{{#if isEven @index}}row{{/if}}">
        <div class="col-lg-6">HELLO</div>
    </div>
{{/each}}

where (similar to @zim suggestion) isEven would be a template helper taking the index as its argument

Template.hello.helpers({
    isEven(index) {
        return index % 2 === 0;
    }
});
1
On

you can get the index and then pass it to a helper to do your logic.

{{#each posts}}
    {{#if isEven @index}}
         <div class="row">
    {{/if}}
             <div class="col-lg-6">HELLO</div>
    {{#if isOdd @index}}
         </div>
    {{/if}}
{{/each}}


Template.foo.helpers({
    isEven(index) {
        return (index % 2 == 0);
    },
    isOdd(index) {
        return (index % 2 == 1);
    }
});

edit:

btw, your if logic looks wrong for matching up the divs. i think you mean something more like this:

{{#each posts}}
    {{#if isEven @index}}
         <div class="row">
    {{else}}
         <div class="col-lg-6">HELLO
    {{/if}}
         </div>
{{/each}}

edit 2:

if Blaze is getting confused by how the divs are formatted, maybe de-confuse it like this. it's easier to read, too:

{{#each posts}}
    {{#if isEven @index}}
         <div class="row">
         </div>
    {{else}}
         <div class="col-lg-6">HELLO
         </div>
    {{/if}}
{{/each}}