Passing data to a subview |
Hi,
i have a subtemplate with the following content: Code: <div> and this is my controller: PHP Code: $view_data['subview'] = $this->load->view('subview',NULL,true); but i got en error "undefined variable name". How can i pass the data to this subview? Is the only way the following solution: (this is the home-view). I prefer only variables in my views and not an call of this->load->view() Code: <div>
This might work:
PHP Code: $view_data['name'] = 'John';
Hi,
that works, but i have to pass the data-array twice. Would it be the better way to call this->load->view directly in the view (like my first example)?
What @mwhitney suggested might work like he said.
But I usually use this lib here to handle template views. Hope it's useful to you... http://jeromejaglale.com/doc/php/codeigniter_template ![]()
Instead of passing the data to the view, you can also just load the data globally and access it in many views.
PHP Code: $data['name'] = 'John'; Now $name and $something_else are available to BOTH view1 and view2. See: http://www.codeigniter.com/user_guide/li...ader::vars (08-28-2015, 11:32 AM)groovebird Wrote: Hi, I must have misunderstood, because I thought you said you prefer not to call $this->load->view() in your view. Something else you could try is not passing the variables to any of your views, and just using $this->load->vars() to set the variables. You still have to set the 'name' portion of $view_data (and call $this->load->vars($view_data), or $this->load->vars('name', 'John')) before you load the views. If you still want to store the result of loading the sub-view in $view_data['subview'], you're still going to have to pass it through to the view (either by calling $this->load->vars() again or passing it to $this->load->view()'s second parameter).
(08-28-2015, 11:47 AM)mwhitney Wrote: I must have misunderstood, because I thought you said you prefer not to call $this->load->view() in your view. You understand me completely right, but if it would be the better solution to call this->load->view in my view, then i would do it. It seems to me a bit easier and cleaner than the other solutions. I don't work so much with CI and i'm a bit uncertain which solution is the best way in this or another case.
Generally, it's better not to call $this->load->view() in the view. On the other hand, you're right in thinking that it's easier to load it in the view. When I choose to call $this->load->view() in my view, I prefer to load the relevant variables into it at the same time, rather than relying on variables being defined beforehand. It also makes it easier to isolate the subview from changes in the controller and view, as I can keep the variable names in the subview the same even if I change everything in the controller and view.
For example: PHP Code: // Controller: |
Welcome Guest, Not a member yet? Register Sign In |