ThinkPHP新版的模板引擎添加了layout试用了下layout功能还是蛮强大的,但还是用法还不太灵活需要在配置文件中手动指定。自己用Behavior做了一个小功能来扩展layout,在Action类中指定$layout属性的值即可自动启用layout,也可以在单个Action方法中设置layout的值,设置为空值时不启用layout。
1.创建ActionEx
文件:Lib/Model/ActionEx.class.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <?php class ActionEx extends Action { public $layout; public $_runViewAssist; public function _initialize() { ActionEx::action($this); add_tag_behavior('view_begin','ViewAssist'); } static public $_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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?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); } } } }
|
4.测试Layout
Lib/Action/TestAction.class.php
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?php class TestAction extends ActionEx { public $layout = '_layout'; public function index() { $this->display(); } public function test2() { $this->layout = ''; $this->display(); } }
|
Tpl/_layout.html
1 2 3 4 5 6 7 8 9 10 11 12 13
| <!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
Tpl/Test/test2.html
分别访问localhost/Test/index和localhost/Test/test2可以看到启用layout和未启用layout界面。
附:
文件目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| | | |~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/