Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarty how to get a first index from foreach?

Construction is this:

<!-- 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's 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 it's going wrong. In this case all the options elemets has a $limit value. How to make it good? I need only first one.

like image 284
Marius Avatar asked Dec 27 '12 14:12

Marius


3 Answers

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

In these cases you can use the @index, @iteration or @first properties. More details are in the smarty foreach documentation at http://www.smarty.net/docs/en/language.function.foreach.tpl#foreach.property.iteration

One of the possible solutions to your question is bellow:

{foreach $rows as $row}
    {if $row@iteration == 1}
        First item in my array          
    {/if}            
{/foreach}
like image 178
hdvianna Avatar answered Oct 30 '22 11:10

hdvianna


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}
like image 28
IT Vlogs Avatar answered Oct 30 '22 11:10

IT Vlogs


Could you do this by the array key?

{foreach from=$rows key=i item=row}
     {if $i == 0}
         First item in my array
     {/if}
{/foreach}
like image 6
Ron van der Heijden Avatar answered Oct 30 '22 12:10

Ron van der Heijden