Header and footer in CodeIgniter

good_evening picture good_evening · Mar 2, 2012 · Viewed 119.9k times · Source

I really don't enjoy writing in every controller:

    $this->load->view('templates/header');
    $this->load->view('body');
    $this->load->view('templates/footer');

Is it possible to do, that header and footer would be included automatically and if we need to change it, we could also do that? How do you deal with that? Or it's not a problem in your opinion? Thanks.

Answer

landons picture landons · Mar 3, 2012

Here's what I do:

<?php

/**
 * /application/core/MY_Loader.php
 *
 */
class MY_Loader extends CI_Loader {
    public function template($template_name, $vars = array(), $return = FALSE)
    {
        $content  = $this->view('templates/header', $vars, $return);
        $content .= $this->view($template_name, $vars, $return);
        $content .= $this->view('templates/footer', $vars, $return);

        if ($return)
        {
            return $content;
        }
    }
}

For CI 3.x:

class MY_Loader extends CI_Loader {
    public function template($template_name, $vars = array(), $return = FALSE)
    {
        if($return):
        $content  = $this->view('templates/header', $vars, $return);
        $content .= $this->view($template_name, $vars, $return);
        $content .= $this->view('templates/footer', $vars, $return);

        return $content;
    else:
        $this->view('templates/header', $vars);
        $this->view($template_name, $vars);
        $this->view('templates/footer', $vars);
    endif;
    }
}

Then, in your controller, this is all you have to do:

<?php
$this->load->template('body');