doushaizhen1244 2012-09-01 13:30
浏览 40
已采纳

将数据传递给两个视图

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条回答 默认 最新

  • dpruwm6206 2012-09-01 13:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻看一个题
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)