CodeIgniter Forums
Variables from loaded view - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Variables from loaded view (/showthread.php?tid=61515)



Variables from loaded view - msheath - 04-21-2015

To make a view neater, I have extracted various chunks of the content to other files and then loaded them with

Code:
$this->load->view('extract.php');

and that works fine. However if the extract contains a variable and I want to use the variable outside the extract, codeigniter throws an error and says the variable is undefined.

How can I achieve this?


RE: Variables from loaded view - pompeu - 04-21-2015

Hi msheath,

as you are passing the variable ? the variable is in the view or the controller?


RE: Variables from loaded view - InsiteFX - 04-22-2015

You can also set global view variables using:

PHP Code:
$this->load->vars($data); 

Any view you create can use them then, if you need them global to your app then you will need a registry class library.


RE: Variables from loaded view - msheath - 04-22-2015

[quote='InsiteFX' pid='317143' dateline='1429699847']

Many thanks for your advice but my issue is this. I have a long code element getting data from a db and setting a number of variables equal to certain data. There are a number of pages requiring the same variables and therefore the same code element, so to be more DRY I wanted to extract the code element to a separate file and load it into every page that needs it.

The variables depend on what is pulled in from the db so I can't set them upfront as global variables. Instead I want to load the code element as well as the variables. In fact want to load in this code element so that it behaves just as if it was originally part of the view.

Sorry if this seems a dumb question.


RE: Variables from loaded view - mwhitney - 04-23-2015

http://www.codeigniter.com/user_guide/libraries/loader.html#CI_Loader::view

Code:
$this->load->view('extract', $data);

You can also use isset() and/or empty() within the view to determine whether specific variables were set before trying to use them.

In general, though, it sounds like you're trying to put Controller or Library code into a View. It might be difficult in the short term, but it would probably be better in the long term to get as much of the code as possible out of the views.


RE: Variables from loaded view - msheath - 04-23-2015

[quote='mwhitney' pid='317284' dateline='1429815068']

Thanks for that which has cleared my mind. I'm sure you're right on reflection. Maybe even go back to the model, set the variables and then pull them in in an array.