[eluser]axiom82[/eluser]
Tired of loading your header and footer above and below your controller method's primary view? This simple solution will solve your coding needs!
1. Place this code into
/application/libraries/Template.php:
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Template {
var $prepend_views = array();
var $append_views = array();
function __construct(){
$this->ci =& get_instance();
}
function prepend($view){
if (!empty($view)){
$this->prepend_views[] = $view;
}
}
function append($view){
if (!empty($view)){
$this->append_views[] = $view;
}
}
function build($view, $data = null){
if (count($this->prepend_views)){
foreach ($this->prepend_views as $prepend_view){
$this->ci->load->view($prepend_view, $data);
}
}
$this->ci->load->view($view, $data);
if (count($this->append_views)){
foreach ($this->append_views as $append_view){
$this->ci->load->view($append_view, $data);
}
}
}
}
/* End of file template.php */
/* Location: ./application/libraries/template.php */
2. Extend the base controller by placing this code into
/application/libraries/MY_Controller.php:
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Template_Controller extends Controller {
function __construct(){
parent::__construct();
$this->load->library('template');
$this->template->prepend('header');
$this->template->append('footer');
}
}
/* End of file MY_Controller.php */
/* Location: ./application/libraries/MY_Controller.php */
3. In your controller, place this code to build your template within a primary view:
Code:
class Your_Controller extends Template_Controller {
function your_method(){
$data = array(
'title' => 'Page Title',
'content' => 'Hello, world!'
};
$this->template->build('your_view', $data);
}
}
That's it! Enjoy this simple template library that sits invisibly below your controller.