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}

 

Site development

About Saurus API / Creating page template tutorial / Creating content template tutorial / Applying custom design to page template checklist / Moderated comments / Stationary articles (header, footer etc) / First, last and n'th item in a foreach loop / Creating zebra tables (cycling values) / Site and Article editor CSS styles / How to set up website aliases / Customising v-shaped editor buttons / Using PHP in templates / Exchanging variables between templates and PHP / Profiles and Custom Assets / Site languages / Printer friendly pages / Enabling browser cache / Creating WAP pages / Configuring sitemap / Saurus 4.1 technical notes