Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method of including views within views in CodeIgniter

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?

like image 909
David Avatar asked Mar 05 '13 10:03

David


People also ask

How to load view in another view in CodeIgniter?

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); ?>

How to include view file in another view file in CodeIgniter 4?

Using $this->load->view() method to load multiple views and define in the order you want to display on the screen in the controller. Create home_view. php file in application/views directory.


1 Answers

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!

like image 96
sandip Avatar answered Sep 18 '22 03:09

sandip