smartysmarty2

Smarty: How to do X when foreach hits half of total


In smarty [v2 to my knowledge] I can not figure i can present some data in a foreach loop when it is halfway through. Ie. separate the first half of array and the second half of the array into two different div elements.

This is where I currently am, and is the logic to what I am trying to accomplish..

    <div>
{foreach from=$feature.variants item="var" name="var"}
    {if $smarty.foreach.var.iteration == ($smarty.foreach.var.total % 2)}
    </div>
    <div class="ty-product-feature__value">
    {/if}
    {$var.variant}
{/foreach}
    </div>

I have everything correct except line 2. I cannot figure out how to properly set it to activate when the current loop iteration equals half of the total amount of times the foreach will loop [meaning regardless of the items it the array, it will put half in one div element and the other half in a second div element.

Also, this is less of a priority but what happens when an uneven array total is present and it can't divided equally in half?

Thank you so much in advance! This is beyond my expertise and am sure there is someone with a better understanding of this than me.


Solution

  • % is for modulus, so the condition is triggering every two items, and that's not what you want. Instead try to check if the current iteration is in the middle of the total number of items in the array. Use ceil so the result of the division is always an integer rounded up:

    {assign var="loop_middle" value=$feature.variants|@count/2}
    {foreach from=$feature.variants item="var" name="var"}
       {$var.variant}
       {if $smarty.foreach.var.iteration == $loop_middle|ceil}
          </div>
          <div class="ty-product-feature__value">
       {/if}
    {/foreach}
    

    So i.e. if you have 11 items, you will end up with two divs, one with 6 items an another with 5