CodeIgniter Forums
Use variables from controller in views - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Use variables from controller in views (/showthread.php?tid=2141)



Use variables from controller in views - El Forum - 07-18-2007

[eluser]woracal[/eluser]
Maybe a stupid question. How do I use variables from a controller in a view? Appreciate any help. Thanks!


Use variables from controller in views - El Forum - 07-18-2007

[eluser]Glen Swinfield[/eluser]
When you load the view, pass your vars in an array:

Code:
$to_controller['variable_one'];
$to_controller['variable_two'];
$to_controller['variable_three'];
$this->load->view('myview', $to_controller);

Then in your view use $variable_one etc to access the variables.

EDIT: should have named that variable $to_view or $from_controller for clarity - I don't know what I was thinking - it will still work though..


Use variables from controller in views - El Forum - 07-18-2007

[eluser]Iksander[/eluser]
Reading the documentation should help a great deal as well - it is very clear and has good examples.


Use variables from controller in views - El Forum - 02-18-2009

[eluser]amey[/eluser]
Hi,

Passing variables from controller to view is not working for me. When I try to print the variables in the view, it throws up a notice "undefined variables"

Controller:
$this->template->load("view", $variable);

View(view.php):
&lt;?php echo "<pre>"; print_r($variable); echo "</pre>"; ?&gt;

Any help would be appreciated.

Thanks.

-Amey


Use variables from controller in views - El Forum - 02-18-2009

[eluser]pistolPete[/eluser]
Read the User Guide!
Quote:Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function.



Use variables from controller in views - El Forum - 02-18-2009

[eluser]amey[/eluser]
Hi,

Thank you for the reply.

In the example above $variable is indeed an array.

I have used this before and it used to work.

It has suddenly stopped working.

Could there be any known reason for this?

Thanks again for your help.

-Amey.


Use variables from controller in views - El Forum - 02-18-2009

[eluser]pistolPete[/eluser]
If it is an array in you controller, you do not access it as an array in your view!

Code:
$data = array(
               'first' => 'abc',
               'second' => 'xyz');

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

In your view, you now access the variables $first and $second, which are the keys oft the assoc array $data.
Code:
echo $first.' - '.$second;