Reputation: 399
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?
Upvotes: 0
Views: 1540
Reputation: 399
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.
Upvotes: 0
Reputation: 41
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);
Upvotes: 1
Reputation: 41
$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');
Upvotes: 0