How can I increment a Smarty variable?

alex picture alex · Jan 5, 2011 · Viewed 36.2k times · Source

I am not usually a Smarty guy, so I'm a bit stuck.

I want to echo the index of an array, but I want to increment it each time I echo it.

This is what I have...

<ul>
    {foreach from=$gallery key=index item=image}
    <li>
        <img src="{$image}" alt="" id="panel-{$index++}" />
    </li>
    {/foreach}
</ul>

It doesn't work.

Is the best way to do this to pre-process the array before handing it to Smarty?

Is there a way I can do this using Smarty?

Answer

Russell Dias picture Russell Dias · Jan 5, 2011

You can do something like the following:

<ul>
    {foreach from=$gallery key=index item=image name=count}
    <li>
        <img src="{$image}" alt="" id="panel-{$smarty.foreach.count.index}" />
    </li>
    {/foreach}
</ul>

Starting from zero, index is the current array index.

That's probably the best way to go about it, however, to simply use a counter outside of a foreach loop you can use counter, like so:

{counter start=0 skip=1 assign="count"}

To increment it simply call {counter} at each iteration.

{counter}
{*Can then use the $count var*}
   {if $count is div by 4}
      {*do stuff*}
   {/if}