ThinkPHP新版的模板引擎添加了layout试用了下layout功能还是蛮强大的,但还是用法还不太灵活需要在配置文件中手动指定。自己用Behavior做了一个小功能来扩展layout,在Action类中指定$layout属性的值即可自动启用layout,也可以在单个Action方法中设置layout的值,设置为空值时不启用layout。
1. 创建ActionEx
文件:Lib/Model/ActionEx.class.php
<?php
class ActionEx extends Action {
public $layout;
public $_runViewAssist;
// 初始化动作绑定
public function _initialize() {
ActionEx::action($this);
add_tag_behavior('view_begin','ViewAssist');
}
// 暂存action
static public $_action;
// 获取action
static function action(&$action = false) {
if ($action) {
self::$_action = $action;
}
return self::$_action;
}
}
?>
2. 配置自动加载路径
在Conf/config.php中添加 'APP_AUTOLOAD_PATH' => '@.Model', 将Model添加到自动加载路径。
3. 添加Behavior
Lib/Behavior/ViewAssistBehavior.class.php
<?php
class ViewAssistBehavior extends Behavior {
protected $options = array();
public function run(&$params) {
$act = ActionEx::action();
if (!$act->_runViewAssist) {
$act->_runViewAssist = true;
if ($act->layout) {
C('LAYOUT_ON', 1);
C('LAYOUT_NAME', $act->layout);
// var_dump($act->layout);exit;
}
}
}
}
?>
4. 测试Layout
Lib/Action/TestAction.class.php
<?php
class TestAction extends ActionEx {
public $layout = '_layout';
public function index() {
$this->display();
}
public function test2() {
// 禁用layout
$this->layout = '';
$this->display();
}
}
?>
Tpl/_layout.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>这是layout</h1>
<div>
{__CONTENT__}
</div>
</body>
</html>
Tpl/Test/index.html
<h3>这是action中的内容</h3>
Tpl/Test/test2.html
<h3>test2</h3>
分别访问localhost/Test/index和localhost/Test/test2可以看到启用layout和未启用layout界面。
附:
文件目录
| | |~Common/ | | |~Conf/ | | | `-config.php | | |~Lang/ | | |~Lib/ | | | |~Action/ | | | | |-IndexAction.class.php | | | | `-TestAction.class.php | | | |~Behavior/ | | | | `-ViewAssistBehavior.class.php | | | |~Model/ | | | | `-ActionEx.class.php | | | `~Widget/ | | |+Runtime/ | | |~Tpl/ | | | |~Test/ | | | | |-index.html | | | | `-test2.html | | | `-_layout.html | | `-index.php
启用Layout和禁用Layout的截图


相关链接
ThinkPHP官网:http://www.thinkphp.cn/