Zebra Tables In Zend Framework

I came across this today at work:

<?php $rowClass = '#f0f0f0' ?>
<table>
<?php foreach($this->books as $book) { ?>
   <?php $i = 0; ?>
   <tr class = "<?php echo $rowClass ?>">
      <td><?php echo $book['author'] ?></td>
   </tr>
   <?php
      if ($i % 2 == 0)
         $rowClass = '#ffffff';
      else
         $rowClass = '#f0f0f0';
      $i++;
    ?>
<?php } ?>
</table>

Zebra tables! Written like a five year old!

For a split second I longed for Smarty’s {cycle} function. Does ZF have something similar? Well of course it does, and it’s even has the word ‘cycle’ in it!

<? $cycle=$this->cycle(array("#F0F0F0","#FFFFFF"));?>
<? foreach ($this->books as $book):?>
  <tr style="background-color:<?=$cycle->next()?>">
  <td><?=$this->escape($book['author']) ?></td>
</tr>
<? endforeach;?>

As a sidenote: ZF’s view helpers are so_much_cleaner than Smarty’s custom functions…

What’s Smarty?

Six months later… and I don’t miss Smarty at all. I’m perfectly happy with Zend Framework’s view scripts and PHP’s alternate syntax tags. Accepting view scripts was easy enough, it’s part of the framework so I might as well use it. However I still couldn’t accept seeing PHP code in my HTML templates:

<table>
<?php foreach($tableData as $dataRow) { ?>
   <tr>
   <?php foreach($dataRow as $data) { ?>
      <td><?php echo $data; ?></td>
   <?php } ?>
   </tr>
<?php } ?>
</table>

When I discovered PHP’s alternate syntax, it just made sense. Especially if one keeps the alternate syntax in the view script only. And I think the syntax itself is much easier for The Designer (who doesn’t know/care about anything that is PHP) to understand:

<table>
<? foreach($tableData as $dataRow): ?>
   <tr>
   <? foreach($dataRow as $data): ?>
      <td><?= $data ?></td>
   <? endforeach; ?>
   </tr>
<? endforeach; ?>
</table>

And at the same time I don’t get asked those endless ‘what the hell does {section} mean?’ questions anymore.