• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variables from loaded view

#1
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?
Reply

#2
Hi msheath,

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

#3
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.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#4
[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.
Reply

#5
http://www.codeigniter.com/user_guide/li...ader::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.
Reply

#6
[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.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.