CodeIgniter Forums
Codeigniter $data var for each view template - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Codeigniter $data var for each view template (/showthread.php?tid=60476)



Codeigniter $data var for each view template - El Forum - 04-04-2014

[eluser]jcjc[/eluser]
I'm passing $data into a view on each page and have an autoload in place. Before the view I have the following:

Code:
$data['category'] = $this->productModel->listCategories();

I'm trying to find a way where I don't have to have this on each page view controller. I've tried placing the code inside the header.php template but I get undefined variable category.

Inside the header template I have:

Code:
<?php foreach ($category as $cat) : ?>
          <li><a href="/products/&lt;?php echo url_title($cat-&gt;ProductCategory, '-', TRUE); ?&gt;">&lt;?php echo $cat->ProductCategory; ?&gt;</a></li>
        &lt;?php endforeach; ?&gt;

Totally stumped!

In short, I need it to run on every page as it's in the header.


Codeigniter $data var for each view template - El Forum - 04-04-2014

[eluser]InsiteFX[/eluser]
When doing multiple views in a file, do this in your controller.

Code:
$data = array(
    'title' => 'My Title',
);

$this->load->vars($data);    // make global to all view files.
$this->load->view('your_main_view');    // do not pass $data in here



Codeigniter $data var for each view template - El Forum - 04-04-2014

[eluser]jcjc[/eluser]
Not multiple views, I have a header.php within a layout folder. Inside the header.php is the following code:

Code:
&lt;?php foreach ($category as $cat) : ?&gt;
          <li><a href="/products/&lt;?php echo url_title($cat-&gt;ProductCategory, '-', TRUE); ?&gt;">&lt;?php echo $cat->ProductCategory; ?&gt;</a></li>
        &lt;?php endforeach; ?&gt;

Inside my controller I have the following code:

Code:
$data['category'] = $this->productModel->listCategories();


Now my issue is that I have multiple controllers that need to call the code in the second block. for the moment I would have to call this code inside every controller I create causing bloat. Is there a way in which I can have the code above "echo'd" out on the header.php without having to pass $data via each controller?



Codeigniter $data var for each view template - El Forum - 04-05-2014

[eluser]InsiteFX[/eluser]
Then create a MY_Controller