我希望每个控制器都有一个方法_render_page,它加载主模板并传递数据对象。
我的家庭控制器类看起来像这样:
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 :(得分:0)
看,你需要了解流程,
当你把你的班级叫回家时,它会扩展MY_Controller,CI会查找MY_Controller,你的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
}
}
答案 1 :(得分:0)
找到解决方案:我以错误的方式调用_render_page。 而不是:
$this->_render_page($this->layout, $data);
我应该这样打电话:
$this->_render_page('welcome_message', $data);
当然,这就是这个函数的用途 - 加载母版页并将视图名称作为$ data的成员传递,因此母版页将知道要加载哪个视图。