[eluser]FireStarter[/eluser]
Hi,
I have decided to start using CodeIgniter and couldn't really find a neat and simple way to run templates. I didn't want to load different views in the controller, nor load header and footer views within a view - or anything like that in fact.
I wanted it to be really simple - have a template, then be able to drop a body view into that template, with both the template and the body view having access to all data.
The solution? Since I couldn't find this anywhere else and it's very basic, just extend the Loader class. Place the following code in ./application/core/MY_Loader.php.
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader {
public function view($template, $view, $vars = array(), $return = FALSE) {
if($template) {
$vars['body'] = parent::view($view, $vars, true);
return parent::view('templates/'.$template, $vars, $return);
} else {
return parent::view($view, $vars, $return);
}
}
}
/* End of file MY_Loader.php */
/* Location: ./application/core/MY_Loader.php */
You can then use it as so:
Code:
// To load a view as normal if you ever need to
$this->load->view(false,'my_view',$data);
// To load a view within a template
$this->load->view('my_template','my_view',$data);
Just place your templates in the ./application/views/template/ directory, this is your HTML template and should somewhere echo the $body variable, which will contain your body view. For example the template 'my_template' would be at ./application/views/template/my_template.
I use it in a basic site where there is a general marketing area and a separate account area.
Code:
// In the marketing area on the contact page
$this->load->view('main','contact');
// In the account area on the foobar page
$this->load->view('account','foobar');
I hope other people find this useful. Sometimes heavy theme/template libraries simply aren't necessary and going back to basics works pretty well, it did for me anyway.
Cheers