CodeIgniter Load Multiple Views / View Inside View

On 9/09/2016

This codeigniter tutorial will show you how to load multiple views in controller or load view inside another view in codeigniter. A view can be a complete webpage or just a part of it like header, footer, menu bar, body content etc. They are flexible in nature and can be nested inside one another.

Views should never be called directly in code igniter but loaded via controllers. And the framework allows you to load multiple views simultaneously or load view within view directly. Both the methods deliver same results but their approach is slightly different. We'll see about them here.


Loading Multiple Views in Codeigniter:

In codeignitor, you must load the views using the function $this->load->view() inside controller. When you make multiple calls to this function, codeingiter cleverly appends them together and display it as one. Here is the example of doing it.

<?php
class my_controller extends Controller {

    ...
    ...
    
    function index()
    {
        $this->load->view("header_view");
        $this->load->view("main_content_view");
        $this->load->view("footer_view");
    }
}
?>

Codeigniter Load View Inside Another View:

As for this approach instead of loading the view from the controller you have to load it directly in another view. Just return the inner view (view to be included) as string and pass it to the outer view.


In your controller you have to add this,

<?php
$data['left_menu'] = $this->load->view('left_menu', '', TRUE);
$this->load->view ('user_profile', $data);
?>

The statement $this->load->view('left_menu', '', TRUE); has the third argument as TRUE which makes it to return the view as string rather sending the output to the browser.


Then in the outer view file you must echo the (view) content.

<html>
    <head>
        ...
    </head>
    <body>
        <div id="header">
        </div>
        <div id="main">
            <div><?php echo $left_menu; ?></div>
            <div id="content"></div>
        </div>
        <div id="footer">
        </div>
    </body>
</html>

Like that you can easily load view inside another view in codeigniter.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *