2012-06-12 87 views
2

論詞,你必須直接從你的控制器的構造函數加載一個視圖的可能性的結尾來看,我加載我的網頁的頁眉和頁腳(因爲它是每個相同功能)代碼點火器裝在控制器

class Add extends CI_Controller{ 
    public function __construct() 
    { 
     parent::__construct(); 
     $this->load->helper('url'); 
     $this->load->view('header_view'); 
     $this->load->view('footer_view');  
    } 

    function whatever() 
    { 
     //do stuff 
    } 

} 

但是,這將裝載的裝載我的函數前頁腳視圖,那麼,有沒有辦法做到這一點沒有「手動」裝載每個函數結束的看法?

+0

您可以使用[鉤](http://codeigniter.com/user_guide/general/hooks.html)之前加載頭你的控制器函數(post_controller_constructor)和之後的腳註(post_controller)。 –

+0

@Rocket不能也使用'__destruct()'方法嗎?或者我有這個錯誤的概念? – gorelative

+0

使用** **掛鉤是一種創造性的方法,但它可能會很麻煩,如果你不希望頁眉/頁腳做時間的100%。 –

回答

0

你不應該渲染在構造函數中的任何意見。 CI控制器應該看起來更是這樣的:

class Add extends CI_Controller { 

    public function __construct() 
    { 
     parent::__construct(); 
     $this->load->helper('url'); 
    } 

    function index() 
    { 
     $this->load->view('header_view'); 
     $this->load->view('home_page'); 
     $this->load->view('footer_view'); 
    } 

    function whatever() 
    { 
     /* 
     * Some logic stuff 
     */ 

     $data_for_view = array(
      'product' => 'thing', 
      'foo'  => 'bar' 
     ); 

     $this->load->view('header_view'); 
     $this->load->view('show_other_stuff', $data_for_view); 
     $this->load->view('footer_view'); 
    } 

} 
+0

我想他正試圖避免編寫'$這個 - >負載>視圖( 'header_view');'和'$這個 - >負載>視圖( 'footer_view');'*中*每一個方法。 –

4

我將在主視圖中添加頁眉/頁腳中的數據,或者使用模板庫(我用這個one)。

如果對於功能主視圖;

// in view for html page 
<?php $this->load->view('header'); ?> 
<h1>My Page</h1> 
<?php $this->load->view('footer'); ?> 
+0

模板+1。從文檔:「如果您不喜歡從每個控制器方法調用頁眉,頁腳和其他全局視圖,模板適合您。」 :-) –

+0

另一個極好的選擇! –

0

我想出這個辦法:

class Add extends CI_Controller{ 
    public function __construct() 
    { 
     parent::__construct(); 

     // load some static 
     $this->data['page_footer'] = $this->common_model->get_footer(); 

    } 
    private function view_loader() { 
     //decide what to load based on local environment 
     if(isset($_SESSION['user'])){ 
      $this->load->view('profile_view', $this->data); 
     } else { 
      $this->load->view('unlogged_view', $this->data); 
     } 
    } 


    function index() 
    { 
     $this->data['page_content'] = $this->profile_model->do_stuff(); 

     // call once in every function. this is the only thing to repeat. 
     $this->view_loader(); 
    } 

    }