模板引擎
TookPHP模版引擎是编译型模版引擎,模版文件只编译一次,以后程序会直接采用编译文件,运行效率非常高。
配置项
~~~
'TPL_PATH' => 'View', // 模板目录
'TPL_STYLE' => '', // 风格
'TPL_FIX' => '.html', // 模版文件扩展名
'TPL_TAGS' => array(), // 模板标签
'TPL_ERROR' => 'error', // 错误信息模板
'TPL_SUCCESS' => 'success', // 正确信息模板
'TPL_ENGINE' => 'Tk', // 模板引擎 Tk,Smarty
'TPL_TAG_LEFT' => '<', // 左标签
'TPL_TAG_RIGHT' => '>', // 右标签
~~~
## assign 向视图层分配内容
示例
~~~
$user = array(
array( 'name'=>' 李四 ', 'age'=>33),
array( 'name'=>' 后盾 ', 'age'=>6,)
);
$this->assign('user',$user);
$this->display('index');
~~~
~~~
//以数组形式分配
$data=array('name'=>'内容','url'=>'www.baidu.com');
$this->assign($data);
~~~
### display 显示内容
语法:
~~~
$this->display($tplFile = null, $cacheTime = -1, $cachePath = null, $contentType = "text/html", $show = true)
~~~
| 参数 | 说明 |
| -- | -- |
| tplFile | 模版文件,默认为当前控制器方法 |
| cacheTime | 缓存时间 , 默认为 TPL_CACHE_TIME 配置项值 |
| cachePath | 缓存路径,默认为 APP_CACHE_PATH 常量值 |
| contentType | 文件类型 ( 默认 text/html) |
| show | 是否输出 , false 返回字符串 |
~~~
//显示模板文件:模块/View目录/控制器/web.html
$this->display('web');
//显示模板文件:template 目录中的 list.html
$this->display('template/list');
~~~
~~~
//缓存 秒,设置缓存目录
$this->display('b.html',30,'Cache');
~~~
### fetch() 获得模板解析数据
display() 用于直接显示内容到浏览器,而 fetch() 方法将返回内容
### isCache() 缓存是否失效
isCache() 方法检测缓存是否失。
~~~
class indexController extends \Took\Controller{
function index(){
if(!$this->isCache()){ // 缓存失效时执行
echo ' 没有缓存 ';
}
$this->display('index',60); // 指定缓存时间为 秒
}
}
~~~
如果缓存文件失效则重新查找数据 , 视图缓存可加快大并发时的数据加载问题。
### 读取系统变量
~~~
{$took.get.cid} 读取 $_GET 中的值
{$took.post.cid} 读取 $_POST 中的值
{$took.request.cid} 读取 $_REQUEST 中的值
{$took.const.CONTROLLER} 读取系统中的常量
{$took.session.cid} 读取 $_SESSION 中的值
{$took.cookie.cid} 读取 $_COOKIE 中的值
{$took.server.HTTP_HOST} 读取 $_SERVER 中的值
{$took.config.db_host} 读取配置项值
{$took.language.title} 读取语言包值
~~~
### 变量调节器
变量调节器是对变量作用的函数,系统函数与用户自定义函数都可做为变量调节器。
说明:
a. 默认变量是做为第一个参数传递的
b. 如果变量位置不是第一个参数使用 ### 指定
~~~
//使用任意 PHP 函数
//在 TookPHP 框架中可以使用任意 PHP 函数做为变量调节器使用
`{$data|strtoupper}`
~~~
~~~
//变量调节器链式操作,例:
{$data|substr=2,8|strtolower}
~~~
~~~
//日期 ( 变量值不是第一个位置)
{$feild.date|date='Y-m-d',###}
~~~
~~~
//截取字符
//截取 个字符标题,后面以 ... 结束
//{$field.title|cutstr=10,'...'}
~~~
~~~
//日期输出当前时间
{:date('Y-m-d')}
~~~
~~~
//使用系统 date 函数
{$date|date='Y-m-d',###}
//输出“年 - 月 - 日”格式的时间
~~~
~~~
{$date|std_date}
//输出“年 - 月 - 日 时 : 分 : 表”格式的时间
{$date|std_date='y-m-d h:i:s'}
~~~
~~~
//使用 date 函数输出
{$date|date='y-m-d h:i:s',###}
~~~
### 模板中使用函数
TookPHP框架支持在模板视图中使用任意函数
注意 : 函数名前加 |,如 `{|substr='baidu.com',0,2}`
### 使用函数
~~~
//地址解析
{:U('index','username=admin&sex=男')}
~~~
~~~
//打印分配的变量
{|show=$data}
或
{:show($data)}
~~~
### default 默认值
当变量为空时用默认值替代
~~~
//示例
{$test|default='默认值'}
~~~