the most awesome guy ever.

The Blog of Darryl E. Clarke

  Random musings from a jaded coder who just needs a hug.

Rendering Loops, the Easy Way

I’d like to say I’m an idiot and should have known how to do this a long long time ago, but since the Zend Framework is so huge – I’m letting it slip by.

Normally I’ve always rendered repetitive data by using a foreach on my objects or arrays and then within that foreach I usually render an external file (when I’m not lazy), or even just have a large chunk of html within my view scripts.  When it comes to bigger sites, I want the html fragments to be as simplified and manageable as possible…

That’s where the Parital and PartialLoop view helpers in Zend Framework come in to play.

Before I would have something like this littered throughout:

<ul>
<?php
foreach ($this->rowset as $row):
    echo '<li>' . $row->title . '</li>';
endforeach;
?>
</ul>

Now that I’ve noted the Partial and PartialLoop helpers I can do this:

<ul>
<?php
echo $this->partialLoop('_my_list.phtml', $this->rowset);
?>
</ul>

And get the same result.  As long as ‘_my_list.phtml’ exists in the module scripts folder and contains the necessary fragment to output data from the row, it should work as planned.

One thing to note though, is that the scope of each row that you are iterating through is that of the partial script fragment ($this) – in my original all included way, the context of the row was ‘$row

My fragment would look like this:

<li><?php echo $this->title; ?></li>

The partialLoop also has a counter that allows you to know what row you are on and do things such as alternate background colours, repeat headers, or whatever else you feel necessary.  Super handy for data set listings.  I hope that makes some sense.

Tags: , , ,