Search code examples
phpperlsmartytemplate-toolkit

Template Toolkit loop.index in foreach converted to Smarty?


I am working on converting a template toolkit project in Perl to PHP with Smarty. However I have been trying to find the equivalent of [% IF loop.index % 2 %] within a foreach loop for Smarty. I appreciate the answers.


Solution

  • If you're simply looking to alternate a display by even/odd in Smarty, which I assume from the '%' modulus operator (though I'm not familiar with Perl):

    {* Smarty template code *}
    {foreach from=$myArray item=foo}
      <tr class="{cycle values="row_even, row_odd"}"><td>{$foo}</td></tr>
    {/foreach}
    

    Alternatively, if you really care about the index value of an array variable ...

    {* Smarty template code *}
    {foreach from=$myArray key=k item=v}
      {if $k % 2}<li>odd</li>{else}even{/if}
    {/foreach}