0

I know how to pass data to a page view via a data array in the controller but I am using a template which loads a nav view independently of the controller like this:

echo isset($nav) ? $this->load->view($nav) : '';

I want to pass dynamic data to the nav view but I don't want to load it separately for every page via the controller data array which would not be very DRY. Is there a way to pass it via code in the template?

Perkin5
  • 401
  • 5
  • 23
  • ha thats funny i was literally just writing about this! check this answer out and if you have any other questions respond... http://stackoverflow.com/a/28819778/1004319 – cartalot Mar 02 '15 at 21:43

3 Answers3

1

Next solution:

Model:

class Model_Index extends CI_Model {

    function __construct() {
        parent::__construct();
    }
    function get_data() {

        $sql = "...";

        $query = $this->db->query($sql);

        return ($query->num_rows()>0) ? $query->result() : false;

     }
}

View:

$this->ci =& get_instance();
$this->ci->load->model('model_index');
$data = $this->ci->model_index->get_data();

print_r($data);
Toth Zsolt
  • 41
  • 1
0
$this->load->view({template}, {vars});

{template} - template file name
{vars} - array for template

sample:

$vars['title'] = 'Hello World';
$this->load->view('test', $vars);

This code load template from application/views/test.php and will use $title variable.

Use in template to load other template:

$this->view('other');
Toth Zsolt
  • 41
  • 1
  • OK that works but I want to pull data from a database so I want $vars to contain an object got from the model. At the moment I am loading the template view from the controller and $data tells the template which sub-view to load. $data currently includes the nav data object too but I don't want to have to keep repeating that for every view. When the template loads the nav sub-view, I would like to pull in the nav object just once at that stage - but I don't know if it is possible. – Perkin5 Mar 03 '15 at 22:18
0

Thanks for this elegant solution to the problem!

After more brain wracking, I came up with another way of handling it in a less comprehensive way by declaring the $data variable at the start of the Controller and then adding common data elements in the Constructor. You can then add special-to-view data elements to the same array in the view method and the whole lot gets sent to the view. That saves adding common data elements in every view method although it obviously only works for the views loaded by that Controller. Useful though.

Perkin5
  • 401
  • 5
  • 23