First, last and n'th item in a foreach loop

Smarty engine provides easy way to determine if an item is first or last in a foreach loop. This is achieved by naming the loop and using the first or last boolean variables.

Next example makes the first article headline bold:

{init_articles name="articles"}

{foreach from=$articles item="article" name="articles_loop"}
   
    {if $smarty.foreach.articles_loop.first}<b>{/if}
        <a href="{$article->href}">{$article->title}</a>
    {if $smarty.foreach.articles_loop.first}</b>{/if}
   
    <br>

{/foreach}

The same applies to "last".

To get the number of an iteration in a foreach loop use the "iteration" variable. This example numerates article headlines:

{init_articles name="articles"}

{foreach from=$articles item="article" name="articles_loop"}
   
    {$smarty.foreach.articles_loop.iteration}. <a href="{$article->href}">{$article->title}</a><br>

{/foreach}