将数据传递给两个视图

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);

1个回答

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.

douhao3562
douhao3562 好吧,我不确定你是什么意思,“没有加载”。 $ this-> load-> view('index',$ data,TRUE); 将$ data传递给索引视图而不打印视图。 就像上面例子中的“侧边栏”视图一样
大约 8 年之前 回复
douyouyi8878
douyouyi8878 我看到你在说什么,但我需要将数据传递给索引视图而不加载它。 其他方式就像我加载post,$ data。我需要从post视图获取$ data变量到索引视图。
大约 8 年之前 回复
dongxian8858
dongxian8858 好的,你能解释一下如何将它传递给索引和发布视图文件
大约 8 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐