Pascal Cloverfield Pascal Cloverfield - 3 months ago 15
Smarty Question

Smarty foreach iteration new column every nth time

I know that question was answered but in a little different way.

I want a new bootstrap column every 6th time of a loop so it looks like this:

<div class="row">
<div class="col-xs-6">
<a href="#">LINK1</a>
<a href="#">LINK2</a>
<a href="#">LINK3</a>
<a href="#">LINK4</a>
<a href="#">LINK5</a>
<a href="#">LINK6</a>
</div>
<div class="col-xs-6">
<a href="#">LINK7</a>
<a href="#">LINK8</a>
<a href="#">LINK9</a>
<a href="#">LINK10</a>
<a href="#">LINK11</a>
<a href="#">LINK12</a>
</div>
</div>


I've tried:

<div class="row">
{foreach name='sub_categories' from=$sub_categories item='sub'}
{if $smarty.foreach.sub_categories.first or $smarty.foreach.sub_categories.iteration is div by 6}
<div class="col-xs-6">
{/if}
<a href="#">LINK</a>
{if $smarty.foreach.sub_categories.iteration-1 is div by 6}
</div>
{/if}
{/foreach}
</div>


But that doesn't work, because:

$smarty.foreach.sub_categories.iteration is div by 6


is true when the 6th iteration starts so smarty creates a new column after 5 iterations. Also the is not closed the 6th time but the 5th time.

Any suggestions?

Answer

The easiest way is using index instead of iteration, because index starts at 0

<div class="row">
    {foreach name='sub_categories' from=$sub_categories item='sub'}
        {if $smarty.foreach.sub_categories.first or $smarty.foreach.sub_categories.index is div by 6}
        <div class="col-xs-6">
        {/if}
           <a href="#">LINK</a>
        {if $smarty.foreach.sub_categories.last || $smarty.foreach.sub_categories.iteration is div by 6}
        </div>
        {/if}
    {/foreach}
</div>

also you may probably want to check sub_categories.last for the closing div, just in case the number of items is not a multiple of 6, i.e. 9