Smarty how to get the first index from foreach?

The design is as follows:

<!-- projects list --> {if !empty($userObjects)} <select id="projects-list" tabindex="1" name="project"> {if !isset($selected)}<option value="0">Choose project</option>{/if} {foreach from=$userObjects item=v} <option value="{$v.Id}" {if $selected==$v.Id}selected="selected"{/if} }>{$v.Name} {* if it 1st element *} {if $smarty.foreach.v.index == 0} {if isset($limit)}<br /><span id="projlimit">{$limit}</span> {$currency->sign}{/if} {/if} </option> {/foreach} </select> 

as you can see i did

 {if $smarty.foreach.v.index == 0} 

but everything goes wrong. In this case, all options elements have a limit value of $. How to do it well? I only need the first.

+6
source share
3 answers

Can you do this with an array key?

 {foreach from=$rows key=i item=row} {if $i == 0} First item in my array {/if} {/foreach} 
+7
source

I don't want to seem rude, but Bondye's answer will not work in all cases. Since PHP arrays are ordered maps, the value of the first key is not always 0.

In these cases, you can use the @index , @iteration or @first . For more information, see the smarty foreach documentation at http://www.smarty.net/docs/en/language.function.foreach.tpl#foreach.property.iteration

One possible solution to your question:

 {foreach $rows as $row} {if $row@iteration == 1} First item in my array {/if} {/foreach} 
+15
source

You can use this code:

 {foreach from=$userObjects item=v name=obj} {if $smarty.foreach.obj.first} This is the first item {/if} {if $smarty.foreach.obj.last} This is the last item. {/if} {/foreach} 
+9
source

All Articles