dongrong3171 2010-11-10 15:42
浏览 40
已采纳

掌握CodeIgniter - 模板/加载视图

Attempting to learn CI and going through the docs to get a better understanding. Without getting a separate library, I could make a template by including a list of views like so:

$this->load->view('header');
$this->load->view('navigation');
$this->load->view('sidenav_open');
$this->load->view('blocks/userinfo');
$this->load->view('blocks/stats');
$this->load->view('sidenav_close');
$this->load->view('content',$data);
$this->load->view('footer');

This makes sense but would I actually have that on each of my controllers (pages)? Not sure if there is a way to include this in the initial controller (welcome) and then in the others somehow reference it? Or perhaps there is something I am missing completely

  • 写回答

2条回答 默认 最新

  • dongqiuwei8667 2010-11-10 15:56
    关注

    You can load views from within a view file. for example, consider a generic page template called page_template.php:

    <html>
    <body>
      <div id = "header">
          <?php $this->load->view('header');?>
          <?php $this->load->veiw('navigation');?>
      </div>
      <div id = "sidenav">
         <?php $this->load->view('sidenav');?>
      </div>
      <div id = "content">
         <?php echo $content;?>
       </div>
    
      <div id = "footer">
          <?php $this->load->view('footer');?>
     </body>
     </html>
    

    Load your more dynamic areas by making use of codeigniter's abiltiy to return a view as a variable in your controller:

    $template['content'] = $this->load->view('content',$data,TRUE);
    $this->load->view('page_template',$template);
    

    By passing TRUE to the load function, CI will return the data from the view rather than output to the screen.

    Your sidenav section could be it's own view file, sidenav.php, where you have your 'blocks' hard-coded or loaded similar to the above example.

    I've done it both ways, including every stinking bit of views in each controller method, and by using a page template that loads sub-views and dynamic areas, and by far, the second method makes me happier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?