Reputation:
I want to pass a variable from a controller to two view files.
public function post($id) {
$data['query'] = $this->blog_model->get_post($id);
$data['comments'] = $this->blog_model->get_post_comment($id);
$data['post_id'] = $id;
$data['total_comments'] = $this->blog_model->total_comments($id);
I want to pass the [total_comments] variable to the index.php and post.php views. How do I do that? Can I pass data to a view without loading them like this:
$this->load->view('post',$data);
Upvotes: 1
Views: 153
Reputation: 3856
Something along this lines?
$data['post'] = $this->load->view('post',$data, TRUE);
The 'TRUE'
argument tells CI to call your view and place it in a $data['post']
variable. Later on you can use that variable in another view and just print it out.
edit:
I'm not sure how you have organized your controllers and views but lets say something like this. This is just an example:
controller
public function comments() {
$data['comments'] = $this->comments_model->get_all_comments();
$data['someVariable'] = 123;
$this->load->view('header', $data); //load header view
$data['sidebar'] = $this->load->view('sidebar', $data, TRUE); //put sidebar view in a variable, but don't show it immediately
$this->load->view('comments', $data); //load comments view
$this->load->view('footer'. $data); //load footer view
}
Whenever you pass $data
to a controller you are passing the whole $data
array to that view so you can access all of its elements in a view.
For example in your comments.php view you will have $comments
, $someVariable
and $sidebar
variables so you can do whatever you want with them.
In comments.php you'd probably have something like this:
comments.php
<div id="comments">
<?php
foreach($comments as $c){ //print out all found comments
?>
<div class="comment">
<?= $c['commentauthor'] ?> <br />
<?= $c['commenttext'] ?>
</div>
<?php } ?>
</div>
<div id="sidebar">
<?= $sidebar ?> //print out sidebar
</div>
<p> This is some variable: <?= $someVariable ?> </p>
Those same variables are available in the footer view, because you've passed $data to that view
$this->load->view('footer'. $data);
I hope that this makes things a bit more clear to you.
Upvotes: 4