25
votes

Ive been working with CI and I saw on the website of CI you can load a view as a variable part of the data you send to the "main" view, so, according the site (that says a lot of things, and many are not like they say ...ej pagination and others) i did something like this

$data['menu'] = $this->load->view('menu');
$this->load->view ('home',data);

the result of this is that I get an echo of the menu in the top of the site (before starts my body and all) and where should be its nothing, like if were printed before everything... I have no idea honestly of this problem, did anybody had the same problem before?

2

2 Answers

68
votes

Two ways of doing this:

  1. Load it in advance (like you're doing) and pass to the other view

    <?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);
    
  2. Load a view "from within" a view:

    <?php
    // put this in the controller
    $this->load->view('home');
    
    // put this in /application/views/home.php
    $this->view('menu');
    echo 'Other home content';
    
7
votes

Create a helper function

function loadView($view,$data = null){
    $CI = get_instance();
    return $CI->load->view($view,$data);
}

Load the helper in the controller, then use the function in your view to load another one.

<?php 
...
    echo loadView('secondView',$data); // $data array
...
?>