How can I increment a Smarty variable?

前端 未结 6 1134
梦毁少年i
梦毁少年i 2021-02-19 16:02

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...<

6条回答
  •  天涯浪人
    2021-02-19 17:00

    Assuming you run through $foo which is an array with the index and iteration options

    {foreach from=$foo item=bar name=humbug}  
        {$smarty.foreach.humbug.index}
        {$smarty.foreach.humbug.iteration}
    {/foreach}
    

    The first column are the index results, the second column are the iteration results

    0 - 1  
    1 - 2  
    2 - 3  
    3 - 4  
    4 - 5
    

    This means index starts at 0 as its the array index, where as the iteration is the loop iteration count which begins at 1.

    An instance where using the wrong value would cause problems is in displaying something in rows of 4 or any other amount in a table.

    Using index would cause a badly laid out table. You would get an immediate row change on the first iteration of the loop (index 0) which would correct itself at the 5th iteration (index 4) but only within the scope of the current layout, meaning your first row would only have 1 cell in it. every other row would have 4 cells and the data in every cell after the first row would be appearing in the table 4 cells later than it should be doing.

    {if $smarty.foreach.humbug.index is div by 4}
        
    {/if}
    

    Using iteration would lay out the row change properly giving equal rows of 4 until the last iteration or the foreach loop.

    {if $smarty.foreach.humbug.iteration is div by 4}
     
    {/if}
    

    After the foreach loop you would simply add a table row closer to complete the final row.

    I hope this helps somebody out.

提交回复
热议问题