How to alternate table row colours the easy way

September 11, 2009 by Adam · Leave a Comment 

We’ve all seen the familiar code in our baked index files:

<?php
$i = 0;
foreach ($pricings as $pricing):
	$class = null;
	if ($i++ % 2 == 0) {
		$class = ' class="altrow"';
	}
?>
<tr <?php echo $class; ?>>


I’ve always thought that this wasn’t quite as elegant as it should be, and certainly not very DRY, as it was required everywhere you wanted alternate row colours. Well today I came across this nice little CakePHP helper by @markgandolfo for alternating table colours in a very similar way to Rails, which takes the above code and makes it look more like this:

<table>
	<?php foreach($items as $item): ?>
	<tr class="<?php echo $cycle->css(); ?>">
		<td><?php echo $item; ?></td>
	</tr>
	<?php endforeach; ?>
</table>


Much better.

Check it out here: http://github.com/markgandolfo/cakephp_cycle_css/tree/master

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

Related posts:

  1. Good resource for MySQL table types…
  2. Creating a sub-category left menu in Magento (that behaves itself)
  3. Simple “MVC” Javascript for CakePHP
  4. Integrating the Auth Component with a bespoke 3rd party Single Sign-On Service in CakePHP

About Adam
Adam is senior developer for Image+ Ltd in Coventry, England. He has been developing websites for over 10 years, and currently freelances through his own company, Votive Media. Follow him on twitter for more!

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!