继承控制器Frontend中添加:
application/common/contorller/Frontend.php
/**
* 自定义模板
* @var string
*/
protected $layouts = [];
public function _initialize(){
// 如果有使用模板布局
$this->layout = $this->setLayout();
if ($this->layout) {
$this->view->engine->layout('layout/' . $this->layout);
}
}
//多模板匹配
public function getLayout(){
if (!is_array($this->layouts)||empty($this->layouts)){
return $this->layout;
}
$request= Request::instance();
$action = $request->action();
foreach ($this->layouts as $k=>$v){
if (in_array($action, $v)){
return $k;
}
}
return $this->layout;
}
//自定义加载模块
public function setLayout(){
if (!is_array($this->layouts)||empty($this->layouts)){
return $this->layout;
}
$request= Request::instance();
$action = $request->action();
foreach ($this->layouts as $k=>$v){
if (in_array($action, $v)){
return $k;
}
}
return $this->layout;
}
自定义控制器(例):
application/index/contorller/User.php
class User extends Frontend{
//设置默认模板,不需要则留空,仅加载自定义的模板
protected $layout = 'default';
//key:模板名称 value:对应使用该模板的所有方法名
protected $layouts = ['a'=>['index'],'b'=>['profile','changepwd']];
}
网友评论