默認情況下ThinkPHP框架系統默認使用的模板引擎是內置模板引擎,內置模板引擎支持模板文件中采用php原生態代碼和模板標簽的混合使用.
ThinkPHP官方開發文檔說,這種默認的內置模板引擎的性能是高效的,但還不是最佳的,要使模板引擎的性能達到最佳效率,就要使用PHP本身作為模板引擎.
使用PHP本身作為模板引擎其實很簡單,只需在項目的配置文件Conf/config.php上配置:'TMPL_ENGINE_TYPE' =>'PHP'
采用PHP本身作為模板引擎后,意味著你將不能再使在模板文件上使用系統默認使用的模板引擎的模板標簽,你只能使用原生態的php代碼.
下面將通過實例來演示一下,采用PHP本身作為模板引擎后,如何在模板上操作php代碼.下載wblog3.1.2_3博客程序并安裝并安裝(你也可以自建項目)
首先配置項目W3note/Conf/config.php文件添加一項配置項:
- <?php
- return array(
- ...
- 'TMPL_ENGINE_TYPE' =>'PHP',
- ...
- );
- ?>
然后把控制器/W3note/Lib/Action/IndexAction.class.php和對應模板/W3note/Tpl/Index/index.html的代碼清空以待不同的調試之用。
好了,基礎工作已經做好了,接下來是調試記錄.
1、在模板上使用php原生態代碼,IndexAction.class.php控制器代碼:
- <?php
- class IndexAction extends Action {
- public function index(){
- $this->display();
- }
- }
- ?>
index.html模板代碼:
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
- <title>使用原生態的php代碼</title>
- </head>
- <body>
- <?php
- $title= 'www.49028c.com';
- echo $title;//輸出變量
- ?>
- </body>
- </html>
- //輸出:www.49028c.com
像原生態的php代碼一樣,可以在模板上聲明變量并輸出變量,還可以標識代碼注釋,不過需要注意的是,必須使用php開始標志"<?php",用"<php>不行嗎,為什么?接下來你就知道了.
2、控制器代碼同上面,模板代碼如下:
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
- <title>使用原生態的php代碼</title>
- </head>
- <body>
- <php>
- $title='www.49028c.com';
- echo $title;
- </php>
- </body>
- </html>
- //輸出:$title='www.49028c.com'; echo $title;
在模板上把"<?php ?>"換成<php></php>后,結果無法解釋變量,說明不支持<php></php>標簽。
3、在模板上直接使用查詢語句,控制器代碼同1,模板代碼如下:
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
- <title>使用原生態的php代碼</title>
- </head>
- <body>
- <?php
- $vo=M('News')->find();
- echo $vo['title'];
- ?>
- </body>
- </html>
- //輸出:歡迎使用WBlog博客程序
控制器在一邊呆著似乎什么也沒做,模板上竟然可以這樣寫,實在太靈活了!
4、在模板上調用控制器分配的查詢結果,IndexAction.class.php控制器代碼:
- <?php
- class IndexAction extends Action {
- public function index(){
- $vo=M('News')->find();
- $this->assign('vo', $vo);
- $this->display();
- }
- }
- ?>
模板index.html代碼:
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
- <title>使用原生態的php代碼</title>
- </head>
- <body>
- <?php
- echo $vo['title'];
- ?>
- </body>
- </html>
- //輸出:歡迎使用WBlog博客程序
這種情況和系統默認使用的模板引擎時寫法沒什么兩樣.
5、在模板上調用項目函數庫的函數,控制器代碼同1,模板代碼如下:
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
- <title>使用原生態的php代碼</title>
- </head>
- <body>
- <?php
- echo pwdHash('abc');//調用項目/W3note/Common/common.php函數庫的加密函數pwdHash()
- ?>
- </body>
- </html>
- //輸出:af10ef457ed637b91955369297b8e640
擯棄了系統默認模板引擎笨拙(相對來講)的標簽語法,函數的調用是如此簡單.
新聞熱點
疑難解答
圖片精選