2014-04-06 106 views
0

我希望每個控制器都有一個方法_render_page,它加載主模板並傳遞數據對象。Codeigniter爲什麼我無法從MY_Controller加載視圖

我家的控制器類看起來是這樣的:

class Home extends MY_Controller { 

    function __construct() { 
     parent::__construct(); 
    } 

    public function index() { 
     $data['title'] = "Site title"; 
     $data['the_view'] = 'welcome_message'; 
     $this->_render_page($this->layout, $data); 
     //$this->load->view($this->layout, $data); //This works ok.. 
    } 
} 

MY_controller類:

class MY_Controller extends CI_Controller { 

    public $layout; 
    public $viewdata; 

    public function __construct() { 
     parent::__construct(); 
     $this->layout = 'layout/master_template'; 
     $this->viewdata = null; 
    } 

    public function _render_page($view, $data=null, $render=false) { 
     $this->viewdata = $data; 
     $this->viewdata['the_view'] = $view; 
     if($this->ion_auth->logged_in()) { 
      $user_obj = $this->ion_auth->user()->row(); 
      $usr_data['username'] = $user_obj->username; 
      $user_obj = null; 
      $this->viewdata['usr_data'] = $usr_data; 
     } 
     $this->load->view($this->layout, $this->viewdata); //The code crashes here 
    } 
} 

當我瀏覽到家用控制器我什麼也沒得到,只是白色屏幕沒有任何錯誤......

回答

0

看,你需要了解流程, 當你調用你的類的家,它擴展MY_Controller,CI會尋找MY_Controller,構造函數o ˚F您MY_controller被執行之後,CI開始執行您的家庭控制器的構造函數,然後回家控制器的默認方法, 所以爲了讓它工作,你需要調用_render_page() - 更改MY_Controller像 -

class MY_Controller extends CI_Controller { 

    public $layout; 
    public $viewdata; 

    public function __construct() { 
     parent::__construct(); 
     $this->layout = 'layout/master_template'; 
     $this->viewdata = null; 
     $this->_render_page($this->layout, $data=null, $render=false); // call your method 

    } 

    public function _render_page($view, $data=null, $render=false) { 
     $this->viewdata = $data; 
     $this->viewdata['the_view'] = $view; 
     if($this->ion_auth->logged_in()) { 
      $user_obj = $this->ion_auth->user()->row(); 
      $usr_data['username'] = $user_obj->username; 
      $user_obj = null; 
      $this->viewdata['usr_data'] = $usr_data; 
     } 
     $this->load->view($this->layout, $this->viewdata); //The code crashes here 
    } 
} 
+0

它也不起作用。爲什麼我會在父類構造函數中調用render方法? – user568021

+0

@ user568021糾正我,如果我錯了,但如果你不調用該方法將如何執行? – sunny

+0

@ user568021你必須在某處調用它,也許在子類 – sunny

0

找到了解決方案:我以錯誤的方式調用_render_page。 取而代之的是:

$this->_render_page($this->layout, $data); 

我應該叫這樣的:

$this->_render_page('welcome_message', $data); 

當然,這是這個函數是什麼 - 加載母版頁,並通過視圖名稱爲$數據成員,所以主頁面將知道要加載哪個視圖。

+0

atlast你不得不調用_render_page()方法。那就是我說的! – sunny

+0

是的,但爲什麼在_constructor? – user568021

+0

因爲構造函數會自動調用哪個inturn調用_render_page()函數,否則您必須在某處手動調用該方法! – sunny

相關問題