Here\'s a PHP example of mine. Can anyone find a shorter/easier way to do this?
foreach($posts as $post){?>
Using CSS3 you can do something like this:
div:nth-child(odd)
{
background-color: red
}
But better not use that for a few years if you actually want your users to see the color...
It's short enough as it is, but I would probably wrap it into some helper function with a clear name. That way it's more obvious what's going on and you won't have to repeat that logic in all templates where you need it.
i always name my zebra rows "row0" and "row1" - this makes the code a bit simpler.
<?php // you should always use the full opening tag for compatibility
$i = 0;
foreach ($rows as $row) {
echo '<tr class="row' . ($i++ % 2) . '">...</tr>';
}
?>
Just for fun
Assuming you can use CSS3 selectors you can do something like
<div class="posts">
<? foreach($posts as $post){?>
<div>
<?=$post?>
</div>
<? }?>
</div>
<style>
div.posts div:odd{background-color:red;}
</style>
Even with CSS2 support and mootools (javascript library) you can substitute the style with this javascript
<script type="text/javascript">
// obviously this script line should go in a js file in a onload (or onDomReady) function
$$('div.posts div:odd').setStyle('background-color','red');
</script>
If you don't have anything but php a it you can simplify a bit yous code using an array
<? $isodd=array('','odd');
$c=0;
foreach($posts as $post){?>
<div class="<?=$isodd[$c++%2]?>">
<?=$post?>
</div>
<? }?>
Smarty has it inbuilt:
{section name=rows loop=$data}
<tr class="{cycle values="odd,even"}">
<td>{$data[rows]}</td>
</tr>
{/section}
So does Django:
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
<?php ($i%2==1) ? $bgc='#999999' : $bgc='#FFFFFF'; ?>
'<div bgcolor=" bgcolor='.$bgc.'">';