I will create a simple `render` method in MY_Controller that allows for a very simple type of template system. It will auto-determine the the view to be used based on controller/method naming conventions. A simplified version looks a little like this:
Code:
protected function render($data=array(), $layout='')
{
$dir = $this->router->fetch_directory();
if (! empty($dir)) $dir .= '/';
$view = $dir . $this->router->fetch_class() .'/'. $this->router->fetch_method();
$data['view_content'] = $this->load->view($view, $data, TRUE);
$layout = ! empty($layout) ? $layout : 'index';
$this->load->view('theme/'. $layout, $data);
}
My current one is actually a bit more complex than that, and automatically formats and inserts status messages, gets stylesheet and script links to the view, etc.
Then, I have different layout files in the views/theme folder that contain the overall layout, or template, to use. The content of the primary view for that method is made available to the layout in the $view_content variable. A simple layout might be like this:
Code:
$this->load->view('theme/parts/header');
$this->load->view('theme/parts/navbar');
<div class="container">
<?= $view_content; ?>
</div>
$this->load->view('theme/parts/footer');
You can create as many layouts as you need - for example, two-column layouts, or blog specific layouts, etc. But then using them in your controller is a single method call:
Code:
public function index()
{
$this->render();
}
// or
public function index()
{
$data = array();
// Do stuff here that puts data in the $data array
$this->render($data);
}
// or customize the layout use
public function index()
{
$data = array();
// Do stuff here that puts data in the $data array
$this->render($data, 'two_col_left');
}