5

I'm is using PHP smarty templater. I need to create even odd row highlighting. Please, send me example how to do that.

also I have variable:

$smarty.foreach.product.index
7
  • I won't send!! What have you tried ?
    – user1481317
    Jan 22, 2013 at 9:37
  • Did you even try? First hit on Google seems promising: Best way to do: first last odd even
    – jensgram
    Jan 22, 2013 at 9:38
  • 2
    Go to the nearest blackboard and start writing: "I will use google before asking question with answers everywhere". Write this 20 times, and after that go to this link: iinuu.eu/en/it-guru/…
    – Vlad Preda
    Jan 22, 2013 at 9:39
  • have you heard about modulo ?
    – hsz
    Jan 22, 2013 at 9:40
  • 1
    @user - why can't you use the google link? what about it didn't work? have you tried to adapt it to your needs? Also, are you aware that odd/even row colouring can be done in pure CSS; you may not even need to use Smarty for this at all (depending on the browser support you need).
    – SDC
    Jan 22, 2013 at 10:12

3 Answers 3

16

For this kind of situation smarty has method called {cycle}

<table>
{foreach $products as $product}
<tr class="{cycle values="odd,even"}">
   <td>{$product.name}</td>
</tr>
{/foreach}
</table>

The result for this will be:

<table>
<tr class="odd">
   <td>1st product</td>
</tr>
<tr class="even">
   <td>2nd product</td>
</tr>
<tr class="odd">
   <td>3rd product</td>
</tr>
</table>

In you stylesheet file define properties for odd and even lines like this:

tr.even td{background: #CCCCCC;}
tr.odd td{background: #EFEFEF;}
0
3
<table>
{foreach key=i item=row from=$items}
<tr{if $i%2==1} bgcolor=#e4e4e4{/if}><td>{$i}</td></tr>
{/foreach}
</table>
1
  • Its best if you also include some explanation along side your code. Jan 22, 2013 at 10:06
1
{section name=myloop start=0 loop=10 step=1}
<tr class="{if $smarty.section.myloop.index is even}tr_even{else}tr_odd{/if}"><td>{$smarty.section.myloop.index}</td></tr>
{/section}
1
  • This also works with any foreach (based on Brians question): {if $smarty.foreach.product.index is even} I'm even! {else} I'm odd! {/if} Nov 27, 2020 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.