How to access loop counters in Smarty

Sometimes Smarty’s syntax is not quite self-explanatory. Recently I was asked how loop counters can be implemented for foreach-loops. According to the API docs there’s an @iteration directive for this case, such that the following should work:

{foreach from=$yourArray item=row}
  Current iteration: {$yourArray@iteration}

Unfortunately, the value remained 0 regardless of the current loop iteration.

Another (working) approach is to specify a name-attribute for the foreach variable in question and then use the global $smarty object to access current loop variables, e.g.

{foreach from=$yourArray item=row name=rows}
  Current iteration: {$smarty.foreach.rows.iteration}

Thus, simply specify the name-attribute and access loop variables via the $smarty object.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.