Search code examples
phpcodeignitermodel-view-controller

Codeigniter Views with Dynamic Parameters


I load the multiple views from the controller, in order to display a page.

$this->load->view('header');
$this->load->view('content', $data);
$this->load->view('sidebar1', $data1);
$this->load->view('sidebar2', $data2);
$this->load->view('footer');

However I think its not a clean approach. Can it be improved by creating a single main view, for example "views/page" which includes all above views in it. Then instead of calling all the above views, i can call only main view, for example:

$this->load->view('main');

In this case how can I pass the variables for the content, sidebar1 and sidebar2? Thanks


Solution

  • Within my projects, I have a tendency to do:

    $this->load->vars($data);
    $this->load->view('template_name');
    

    Where my template loads in other views within itself.

    The CodeIgniter documentation states the following for the method $this->load->vars():

    "This function takes an associative array as input and generates variables using the PHP extract function. This function produces the same result as using the second parameter of the $this->load->view() function above. The reason you might want to use this function independently is if you would like to set some global variables in the constructor of your controller and have them become available in any view file loaded from any function. You can have multiple calls to this function. The data get cached and merged into one array for conversion to variables. "

    Using $this->load->vars($data) helps in not having to load data for each view within my template.