In my last posting I talked about alternating table row colors with plain PHP. But how is this handled in different frameworks like CakePHP, Zend Framework, Rails or Smarty?
[UPDATE: My CakePHP-Cycle-Helper is described here: http://functino.com/2009/07/cakephp-cycle-helper-alternating-row-colors-with-cake/]
I’m going to show you simple examples for each of this tools.
In Smarty you can alternate table row colors (or any other thing) with the simple cycle function like this:
{section name=rows loop=$animals}
<tr class="{cycle values="odd,even"}">
<td>
{$animals[rows]}
</td>
</tr>
{/section}Ruby on Rails
In Ruby on Rails there is a very similar solution: The cycle helper. Use it like this:
<% @animals.each do |animal| %> <tr class="<%= cycle("even", "odd") %>"> <td> <%= animal.name %> </td> </tr> <% end %>
Documentation is here: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001721
Zend Framework
Within Zend there is currently no such solution in the core. However there is a proposal for a rails-like cycle helper:
<?php $cycle=$this->cycle(array("odd","even"));?> <?php foreach ($this->animals as $animal):?> <tr class="<?=$cycle->next()?>"> <td><?=$animal['name']) ?></td> </tr> <?php endforeach;?>
Instead of just using a cycle-function you have to create an instance of a cycle object and use that. The full proposal is here: http://framework.zend.com/wiki/display/ZFPROP/Zend_View_Helper_Cycle+-+Kamil+Nowakowski
And finally Cake
Cake has no built in cycle helper. If you use the cake bake generator you’ll get code like this for alternating row classes/colors:
<?php $i = 0; foreach ($animals as $animal): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>>
It’s ugly, isn’t it?
Like I said in my last posting, I think this would be a prettier solution:
<?php foreach($animals as $animal):?> <tr <?php echo $class = empty($class) ? ' class="altrow"' : '';?>>
But I think we can do even better: Create a cycle helper for cake that behaves like the solution in Rails, Smarty or Zend. I’ve written a little helper that does exactly that and in my next posting I’m going to show you how I did it.
UPDATE:
My CakePHP-Cycle-Helper is described here:
http://functino.com/2009/07/cakephp-cycle-helper-alternating-row-colors-with-cake/
Subscribe
One ResponseLeave one →
Leave a Reply