清风徐来
知是行之始,行是知之成

改进layout library,方便自定义layout

PHP CodeIgniterlayout 约 1 分钟

CodeIgniter使用 layout library 简化视图布局 中,有些小的缺陷,不能在controller中加载类的同时设定自己的layout。貌似在CI1.6.1时可以的,方式:$this->load->library(’layout’,’template’);自定义的layout就是template。但是现在CI1.7.0+,loader不一样了。 library($library,$paramsAarry,$objName),有三个参数了。第一个必须的是要加载的library,后面的分别是配置数组和自定义对象名称。 所以,$this->load->library(’layout’,’template’)就不适用了。于是清风就把layout library改写了一下。

obj =& get_instance(); if (count($params) > 0) { $this->initialize($params); } else { $this->layout = 'layout_main'; } } function initialize($params = array()) { if (count($params) > 0) { foreach ($params as $key => $val) { $this->$key = $val; } } } function view($view, $data=null, $return=false) { $data['content_for_layout'] = $this->obj->load->view($view,$data,true); if($return) { $output = $this->obj->load->view($this->layout,$data, true); return $output; } else { $this->obj->load->view($this->layout,$data, false); } } } ?> 新的调用方式: function Contact() { parent :: Controller(); # layout不是默认的layout_main.php 了,是newtemplate.php了 $config = array('layout' => 'newtemplate'); $this->load->library('layout',$config); }
function index() {
	$data["page_title"] = "联系我们";
	$this->layout->view('contact', $data);
}
如果想自定义对象名可以这样: function Contact() { parent :: Controller(); $config = array('layout' => 'newtemplate'); $this->load->library('Layout',$config,'mytemp'); }
function index() {
	$data["page_title"] = "联系我们";
	# 下面就是使用自定义的对象名 mytemp
	$this->mytemp->view('contact', $data);
}