Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increment a Smarty variable?

Tags:

php

smarty

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?

like image 855
alex Avatar asked Jan 05 '11 01:01

alex


1 Answers

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}
like image 160
Russell Dias Avatar answered Sep 28 '22 01:09

Russell Dias