简体   繁体   中英

smarty add a counter and check the values and add class

In smarty I want to set a counter value and check it's increment. In simple php the code is like this

$i = 0;
while ( $someValues ) :
$i++;
<div class="test ''.$class.">$number</div>
endwhile;

Now in php I want to add class like this

if($i==1) {
    $class= 'active';
  }
  else {
    $class= '';
  }

In smarty I have the all the values from the database has been assigned to the variable someValues. so here in smarty I will check that like

{foreach from=$someValues item=row}
<div class="test">$row.number</div>
{foreach}

here its giving the result like this

<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>

Now here I want the same type of counter and want to add class. So can someone tell me how to do this? I had tried while loop to check but it showed the total page blank.

indexes from 1 you have in

{$smarty.foreach.name.iteration}

If you want to add class to the first div in foreach, you can simply use

<div class="test{if $smarty.foreach.name.first} first{/if}">text</div>
or
<div class="test{if $smarty.foreach.name.index == 0} first{/if}">text</div>
or
<div class="test{if $smarty.foreach.name.iteration == 1} first{/if}">text</div>

EDIT: More info: http://www.smarty.net/docsv2/en/language.function.foreach.tpl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM