Posted by & filed under CodeIgniter, PHP.

As discussed in the previous post, a better way to load a template is by using a helper function, which loads the header and footer (and any common partials) for each page.

Here’s how our template helper will be.


if ( ! function_exists('renderPage')) {
function renderPage($view,$data){
           $ci = &get_instance();
           $ci->load->view('header');
           $ci->load->view($view,$data);
           $ci->load->view('footer');
       }
}

Save the above code to application/helpers/template_helper.php file.

To use the helper, we do the following in the controller


function home(){
   $this->load->helper('template');
   renderPage('home',array('key'=>'value'));
}

This will load the view we want, without us needing to load the header and footer manually each time.

To make it even easier, you can autoload the helper in config/autoload.php. You’ll not need to load the helper in every controller.

Next, we’ll see how to create WordPress style functions like get_header() and get_footer() for CodeIgniter.

Leave a Reply

  • (will not be published)