views:

51

answers:

1

Hello,

I need to recursively iterate over an array in a view and was wondering what are some best practices for this type of situation? I'm trying to avoid building my desired html output in the controller or model.

FYI I'm using the framework codeigniter.

Thanks for the help!

A: 

There are bound to be varied opinion on how to achieve your end - and much may depend on the complexity of our your structure and how you wish to organize your views.

At its simplest you may wish to use PHP iterative statements in your view. This is commonly seen in basic CI examples where the controller passes data to a view, then a foreach loop outputs the array elements or object properties in the view. Some may dislike using PHP in their views (if, for example, they co-develop with designers afraid of PHP's syntax) or wish to employ CI's (or a 3rd party) tempting class instead. However there is nothing wrong with some PHP in your view. It's been pointed out that PHP is a template language already.

Another approach that works for complex views is to use nested views or concatenating views. You may load a view which has in it a single iterative statement which in turn loads a view with each iteration. Or conversely you can do this iteration in your controller, and simply concatenate the output of each view, like so:

// iterate through a DB result set to create a block of markup
foreach($result_set as $result)
{
  $view_set .= $this->load->view('result_view_1',$result,TRUE); // the third argument allows us to return the output string.
}

// now determine what view will display this bock of markup
$this->load->view('results_page_A',array( 'view_set' => $view_set ));// 

The advantage of this approach is that your views are reusable by other controllers or actions.

Natebot
Thanks for your reply. I will try and implement the recursive views as per your "another appraoch"
simon99