Codeigniter passing data from controller to view
As per here I've got the following controller:
class User extends CI_Controller {
public function Login()
{
//$data->RedirectUrl = $this->input->get_post('ReturnTo');
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('User_Login', $data);
}
//More...
}
and in my User_Login.php
view file I do this:
<?php print_r($data);?>
which results in:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/User_Login.php
Line Number: 1
Do I need to load any specific modules/helpers to get the $data variable populated? If I print_r($this)
, I can see a lot of stuff but none of my data except in caches
Edit: To clarify, I know that calling the variable the same in the controller and view won't "share" it - it's out of scope but in the example 开发者_开发问答I linked, it seems to imply a $data
variable is created in the scope of the view. I simply happened to use the same name in the controller
Ah, the $data
array's keys are converted into variables: try var_dump($title);
for example.
EDIT: this is done using extract.
you should do it like :
echo $title ;
echo $heading;
echo $message;
Or you can use it like array. In Controller:
...
$this->load->view('User_Login', array('data' => $data));
...
In View:
<?php print_r($data);?>
will show you the Array ( [title] => My Title [heading] => My Heading [message] => My Message )
you can pass a variable in the url to
function regresion($value) {
$data['value'] = $value;
$this -> load -> view('cms/template', $data);
}
In the view
<?php print_r($value);?>
You can't print the variable $data as it is an associative array....you may print every element of the associative array.....consider the following example.
Don't do as follows:
echo $data;
Do as follows:
echo $title;
echo $heading;
echo $message;
You can use this way also
$data['data]=array('title'=>'value');
$this->load->view('view.php',$data);
while sending data from controller to view we pass it in array and keys of that arrays are made into variables by code codeigniter and become accessible in view file.
In your code below all keys will become variables in User_Login.php
class User extends CI_Controller {
public function Login()
{
$data = array(
'title' => 'My Title', //In your view it will be $title
'heading' => 'My Heading', //$heading
'message' => 'My Message' //$message
);
$this->load->view('User_Login', $data);
}
}
and in your User_Login.php view you can access them like this:
echo $title;
echo $heading;
echo $message;
精彩评论