Manish Tiwari Manish Tiwari - 5 months ago 28
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

header.php
index.php
footer.php


And i am doing this :

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


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
load->view
can i use it with my requirement OR Include function is best for this ?

Answer

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'] : https://www.codeigniter.com/user_guide/general/views.html#returning-views-as-data example:

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