It is not uncommon to load a common header, footer and other views in each controller. While this can be achieved like so…
$this->load->view('header', $header_data);
$this->load->view('content', $content_data);
$this->load->view('footer', $footer_data);
I wanted the ability to do the same thing with a single line of code. So I decided to extend the core Loader library by creating “application/core/MY_Loader.php” with the following code…
class MY_Loader extends CI_Loader {
/**
* Load Multiple Views
*
* This function is used to load multiple "view" files. It has three parameters:
*
* 1. An array of the "view" file to be included.
* 2. An associative array of data to be extracted for use in the views.
* 3. TRUE/FALSE - whether to return the data or load it. In
* some cases it's advantageous to be able to return data so that
* a developer can process it in some way.
*
* @access public
* @param mixed
* @param array
* @param bool
* @return mixed
*/
function multiview($view = array(), $vars = array(), $return = FALSE)
{
$return_value = '';
if (is_array($view)) {
foreach ($view as $current_index => $current_view) {
$current_vars = $vars;
if (is_array($vars[$current_index])) {
$current_vars = $vars[$current_index];
}
$result = $this->view($current_view, $current_vars, $return);
if (is_string($result)) {
$return_value .= $result;
}
}
return $return_value;
} else {
return $this->view($view, $vars, $return);
}
}
}
/* End of file MY_Loader.php */
/* Location: ./application/core/MY_Loader.php */
Now I can load multiple views with a single call…
$this->load->multiview(array('header','content','footer'), array($header_data, $content_data, $footer_data));
Or simplify the call with all of the data combined (though CI technically does this in the core Loader anyhow).
$this->load->multiview(array('header','content','footer'), $combined_data);
Feel free to use my example in your own project or post up some questions/comments below 😉
Â
Hi,
Thanks for the script it helped me. There’s just one correction that after the completion of the script $return_value is to be returned instead of $result, $result is only returning the last view in the array.
Upon reviewing the code, you are correct. I have updated the example 😉