Search code examples
phpcodeignitercodeigniter-3codeigniter-2

How do I automatically load a header and footer view?


I am new to using CodeIgniter but I do have enough understanding on mvc structure and CodeIgniter itself to do simple things like load views in the controller and auto load libraries e.c.t. But the issue I'm having is I have a header and footer view that I want to be loaded automatically every time I load a view file.

I have done some searching and a lot of suggestions are dated, or sometimes I simply don't understand the solution. I have made my header view and linked my CSS in it, and also created my footer view as well. So lets say I wanted to load the default welcome page like below:

public function index() {
      $this->load->view('welcome_message');
}

I can load them manually like so:

public function index() {
      $this->load->view('common/header');
      $this->load->view('welcome_message');
      $this->load->view('common/footer');
}

But what I would like is to just load the view like normal and have my header and footer loaded with it automatically. I understand this needs to be accomplished using a custom library with a template function of some sort, but I don't know enough to just do that from scratch.


Solution

  • I did this and it works for me.

    MY_Loader.php

    class MY_Loader extends CI_Loader{
        public function template($content,$var=array()){
            $this->view('common/header');
            $this->view($content,$var);
            $this->view('common/footer');
        }
    }
    

    Put it in core folder.

    In your controller :

     public function index(){
       $content = "welcome_message";
       $data = array();
       $data['name'] = "Max";
       $data['country'] = "USA";
       $this->load->template($content,$data);
     }
    

    Call the data in view :

    <html>
      <?php echo $name.' - '.$country; ?>
    </html>