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.

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

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作