Best method of including views within views in CodeIgniter

David picture David · Mar 5, 2013 · Viewed 91.8k times · Source

I'm starting a large codeigniter project and would like to try to create some reusable 'mini' views for snippets of content like loops of data which may be displayed on different pages/controllers.

Is it better to call the views from within the main controller's view? If so, how? Or should I call the 'mini view' from the controller and thus pass the view's code to the main view?

Answer

sandip picture sandip · Mar 5, 2013

Views within other views are called Nested views. There are two ways of including nested views in CodeIgniter:

1. Load a nested view inside the controller

Load the view in advance and pass to the other view. First put this in the controller:

<?php
// the "TRUE" argument tells it to return the content, rather than display it immediately
$data['menu'] = $this->load->view('menu', NULL, TRUE);
$this->load->view ('home', $data);
?>

Then put <?=$menu?> in your view at the point you want the menu to appear.

2. Load a view "from within" a view

First put this in the controller:

<?php
  $this->load->view('home');
?>

Then put this in the /application/views/home.php view:

<?php $this->view('menu'); ?>

<p>Other home content...</p>

About best method, I prefer the 1st method over 2nd one, because by using 1st method I don't have to mix up code, it is not like include php. Although indirectly both are same, the 1st method is clearer & cleaner than 2nd one!