Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check iteration in smarty?

Tags:

foreach

smarty

How can I check the current iteration for foreach and do something?

{foreach $new_products as $product name=foo}
    {if $smarty.foreach.foo.iteration=5}
        Do it!
    {/if}
{/foreach}

This always return not checked

like image 618
skywind Avatar asked Mar 05 '12 08:03

skywind


3 Answers

I think you should do {if $smarty.foreach.foo.iteration == 5} (note the ==).

like image 69
apfelbox Avatar answered Oct 23 '22 20:10

apfelbox


There is an alternative (I think newer) technique for this. The example from the Smarty docs demonstrates it nicely:

{foreach $items as $i}
  {if $i@index eq 3}
     {* put empty table row *}
     <tr><td>nbsp;</td></tr>
  {/if}
  <tr><td>{$i.label}</td></tr>
{/foreach}

Note the index starts from zero, so index 3 is the 4th iteration.

like image 6
Highly Irregular Avatar answered Oct 23 '22 22:10

Highly Irregular


For Smarty 3 you can use the @iteration property

{foreach $new_products as $product}
    {if $product@iteration == 5}
        Do it!
    {/if}
{/foreach}
like image 4
Marcio Mazzucato Avatar answered Oct 23 '22 21:10

Marcio Mazzucato