Manish Tiwari Manish Tiwari - 1 year ago 84
PHP Question

What is best option to load multiple views using Codeigniter?

I want to load multiple view from a function, devided pages into 3 parts


And i am doing this :

$this->load->view('templates/header', $data);

But in this if i want to add some jquery files and of footer.php that is not possible from above code.

I another way that i saw from many articles

Use include function in view index page like this:

<?php include('header.php'); ?>
<?php include('footer.php'); ?>

But If i add few jquery file after footer.php, it's possible in above code (include code).

But i like this
can i use it with my requirement OR Include function is best for this ?

Answer Source

You could use $this-load->view from inside each of your views, not only controllers.

So in your index.php view file, at the top you could load the header, and at the bottom the footer.

I would not use include() in CodeIgniter at all. CI has loaders for everything you need to use inside it.

A better way to do it would be to define a library or model that would load the template.This way, if you want to change the file included at the top or bottom you don't need to change every view. Even more, you can use this load js,css, seo metadata etc. based on each controller.

The way to achieve this is (let's go the model route):

  1. Create a model called TemplateModel with a function render that receives $data.
  2. In $data you can define the keys: js, css, seo, content etc.
  3. Load the layout from inside the model with $this->load->view('template', $data).
  4. In your controller, return your view as data (for example index.php) and send it to the model as $data['content'] : example:

    $this->load-model('templateModel', 'template');
    $data['content'] = $this->load->view('index', '', TRUE);
  5. In the view rendered by your model, print content where it should display (btw header and footer).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download