Smarty
回顾
实现框架类的步骤
第一步:定义路径常量
第二步:导入配置文件
第三步:确定路由
第四步:加载需要的类
第五步:将加载类的方法注册到__autoload()栈中
第六步:请求分发
index.php作用
- 接受请求
- 启动框架
Smarty简介
引入Smarty
在上一讲的视图中,有PHP代码,对前端人员不友好。
最好视图中不要出现PHP代码。PHP代码就在PHP页面中。
Smarty介绍
Smarty是一个PHP开发的模板引擎。
用来分离逻辑代码和外在的内容。
Smarty的工作原理
封装自己的Smarty
准备代码
- 创建1-demo.php页面
<?php
$title=’锄禾日当午’;
require ‘./demo1.html’;
- 创建demo1.html
<!doctype html>
<html>
<head>
<meta charset=”utf-8″>
<title>无标题文档</title>
</head>
<body>
<?php echo $title;?>
</body>
</html>
- 运行结果
封装Smarty(一)
思路:在demo1.html中有PHP代码,在demo1.html页面(模板页面)中去除PHP代码。
实现:
第一步:将模板中的PHP定界符换成{}标签
模板代码如下:
<body>
{$title}
</body>
访问页面,不能解析$title的值
原因:PHP不能识别{ }。
第二步:将{ }转成PHP的定界符。并访问
原因:将替换好的内容当成字符串输出了。
第三步:将替换好的支付串写到混编文件中,并包含到PHP页面中来
封装(一)实现后会出现3个文件:PHP、HTML、混编文件
封装Smarty(二)
在上面的封装中,生成混编文件的代码每显示一个页面都要执行一次。我们需要将这段代码封装到类中
思想:
- 要将变量保存到对象中
- 要通过访问对象的方式来访问变量
字符串替换更改如下:
第一步:创建Smarty.class.php页面
<?php
class Smarty {
private $tpl_var=array(); //私有的属性保存变量的值
//给对象赋值
public function assign($k,$v) {
$this->tpl_var[$k]=$v;
}
//编译,生成混编文件
public function compile($tpl) {
$com_file=$tpl.’.php’; //混编文件的地址
$str=file_get_contents($tpl); //获取模板内容
$str=str_replace(‘{$’,'<?php echo $this->tpl_var[\”,$str); //替换{标签
$str=str_replace(‘}’,’\’];?>’,$str); //替换}标签
file_put_contents($com_file,$str); //将替换好的字符串写到混编文件中
require $com_file;
}
}
第二步:引入Smarty类,并调用方法
这个步骤完成后,一共有4个页面
封装Smarty(三)
在上面的封装中,每执行一次都会编译一下混编文件,这样效率低。
如果混编文件存在,并且混编文件的修改时间>模板文件的修改时间就直接包含,否则创建新的混编文件
<?php
class Smarty {
private $tpl_var=array(); //私有的属性保存变量的值
//给对象赋值
public function assign($k,$v) {
$this->tpl_var[$k]=$v;
}
//编译,生成混编文件
public function compile($tpl) {
$com_file=$tpl.’.php’; //混编文件的地址
/**
*如果文件不存在,或者修改了模板文件就生成混编文件。
*/
if(file_exists($com_file) && filemtime($com_file)>filemtime($tpl))
require $com_file;
else{
$str=file_get_contents($tpl); //获取模板内容
$str=str_replace(‘{$’,'<?php echo $this->tpl_var[\”,$str); //替换{标签
$str=str_replace(‘}’,’\’];?>’,$str); //替换}标签
file_put_contents($com_file,$str); //将替换好的字符串写到混编文件中
require $com_file;
}
}
}
封装Smarty(四)
在上面的封装中,文件没有分类存放。将文件分类存放,创建如下目录
更改Smarty类
<?php
class Smarty {
public $template_dir=’./templates/’; //模板文件夹
public $templatec_dir=’./templates_c/’; //混编文件夹
private $tpl_var=array(); //私有的属性保存变量的值
//给对象赋值
public function assign($k,$v) {
$this->tpl_var[$k]=$v;
}
//编译,生成混编文件
public function compile($tpl) {
$tpl_file=$this->template_dir.$tpl; //拼接模板地址
$com_file=$this->templatec_dir.$tpl.’.php’; //拼接混编文件的地址
/**
*如果文件不存在,或者修改了模板文件就生成混编文件。
*/
if(file_exists($com_file) && filemtime($com_file)>filemtime($tpl_file))
require $com_file;
else{
$str=file_get_contents($tpl_file); //获取模板内容
$str=str_replace(‘{$’,'<?php echo $this->tpl_var[\”,$str); //替换{标签
$str=str_replace(‘}’,’\’];?>’,$str); //替换}标签
file_put_contents($com_file,$str); //将替换好的字符串写到混编文件中
require $com_file;
}
}
}
封装Smarty(五)
一般在封装的时候,核心代码都是私有的,通过共有的方法调用私有方法
<?php
class Smarty {
public $template_dir=’./templates/’; //模板文件夹
public $templatec_dir=’./templates_c/’; //混编文件夹
private $tpl_var=array(); //私有的属性保存变量的值
//给对象赋值
public function assign($k,$v) {
$this->tpl_var[$k]=$v;
}
public function display($tpl) {
require $this->compile($tpl);
}
//编译,生成混编文件
private function compile($tpl) {
$tpl_file=$this->template_dir.$tpl; //拼接模板地址
$com_file=$this->templatec_dir.$tpl.’.php’; //拼接混编文件的地址
/**
*如果文件不存在,或者修改了模板文件就生成混编文件。
*/
if(file_exists($com_file) && filemtime($com_file)>filemtime($tpl_file))
return $com_file;
else{
$str=file_get_contents($tpl_file); //获取模板内容
$str=str_replace(‘{$’,'<?php echo $this->tpl_var[\”,$str); //替换{标签
$str=str_replace(‘}’,’\’];?>’,$str); //替换}标签
file_put_contents($com_file,$str); //将替换好的字符串写到混编文件中
return $com_file;
}
}
}
在PHP页面中,更改调用编译的方法
<?php
require ‘./Smarty/Smarty.class.php’; //引入Smarty类
$title=’锄禾日当午’;
$smarty=new Smarty(); //实例化Smarty
$smarty->template_dir=’./view/’; //定义模板目录
$smarty->templatec_dir=’./view_c/’;
$smarty->assign(‘title’,$title); //给变量赋值
$smarty->display(‘demo1.html’); //编译模板
官方Smarty
到Smarty官网上下载Smarty包(www.smarty.net)
解压
Smarty核心文件夹的目录结构
Smarty.class.php文件
打开Smarty.class.php页面
将libs文件夹拷贝到站点下,并改名为Smarty
Smarty的简单使用
例题
- 创建templates文件夹和templates_c文件夹
- PHP页面
<?php
require ‘./Smarty/Smarty.class.php’;
$smarty=new Smarty(); //实例化
$smarty->setTemplateDir(‘./templates/’); //设置模板文件夹
$smarty->setCompileDir(‘./templates_c/’); //设置混编文件夹
$smarty->left_delimiter='<{‘; //更改左定界符
$smarty->right_delimiter=’}>’; //更改右定界符
$smarty->assign(‘title’,’锄禾日当午’);
$smarty->display(‘demo6.html’);
- html页面
Smarty注释
语法:{* 注释内容 *}
变量
普通变量
普通变量在smarty中有两种定义方式
方法一:在PHP中定义 语法:$smarty->assign(‘变量名’,变量值);
方法二:在模板中定义
保留变量
在Smarty中有个特殊的保留变量$smarty,此变量用于访问用户请求的数据,系统环境变量,常量等等。
表达式 | 说明 |
{$smarty.get.name} | 获取get提交的name的值 |
{$smarty.post.name} | 获取post提交的name的值 |
{$smarty.request.name} | 获取请求(get,post)的name的值 |
{$smarty.const.PI} | 获取PI常量 |
{$smarty.session.name} | 获取会话的name的值 |
{$smarty.cookies.name} | 获取cookie的name的值 |
{$smarty.version} | 获取Smarty的版本 |
{$smarty.ldelim} | 获取左界定 |
{$smarty.rdelim} | 获取右界定 |
例题
PHP代码
<?php
require ‘./Smarty/Smarty.class.php’;
$smarty=new Smarty(); //实例化
define(‘PI’, 3.14);
$_SESSION[‘name’]=’李白’;
setcookie(‘name’,’杜甫’);
$smarty->display(‘demo8.html’);
HTML代码
配置变量
将一些值放到配置文件中,从配置文件中取出变量的值
- 在站点下创建configs文件夹
- 在configs文件夹中创建config.conf文件,代码如下:
- 在模板中引入配置文件
脚下留心:通过{# #}来获取配置文件中的值
变量修饰器
变量修饰器用来处理变量,“|”是管道运算符。将前面的数据作为参数传递到后面。
Smarty中数组访问
Smarty中数组的访问有两种方式:
- 数组名[下标]
- 数组名.下标
PHP代码
<?php
require ‘./Smarty/Smarty.class.php’;
$smarty=new Smarty(); //实例化
$smarty->assign(‘stu’,array(‘tom’,’berry’,’ketty’)); //索引数组
$smarty->assign(’emp’,array(‘name’=>’李白’,’sex’=>’男’)); //关联数组
$smarty->assign(‘goods’,array( //二维数组
array(‘name’=>’手机’,’price’=>22),
array(‘name’=>’笔记本’,’price’=>33)
));
$smarty->display(‘demo11.html’);
HTML代码
内置函数
{assign}:声明变量
{$var=…}:{assign}函数的缩写
{if},{elseif},{else}:判断语句
脚下留心:Smarty中使用的运算符和PHP是完全一致的。
{for}:循环
{while}:循环
{foreach},{foreachelse}:遍历数组
语法:
{foreach 数组 as $k=>$v}
//循环体
{foreachelse}
如果数组为空,就执行这一段(可以省略)
{/foreach}
例题:
PHP代码
<?php
require ‘./Smarty/Smarty.class.php’;
$smarty=new Smarty(); //实例化
$smarty->assign(‘stu’,array(
‘class1’=>’tom’,
‘class2’=>’berry’,
‘class3’=>’ketty’,
‘class4’=>’rose’,
‘class5’=>’李白’,
‘class6’=>’杜甫’,
));
$smarty->display(‘demo13.html’);
HTML代码
{foreach}的属性: @index, @iteration, @first, @last, @show, @total.
<table border=’1′>
<tr>
<th>是否是第一个元素</th><th>索引</th><th>编号</th><th>键</th>
<th>值</th><th>是否在最后一个元素</th>
</tr>
{foreach $stu as $k=>$v}
<tr>
<td>{[email protected]}</td>
<td>{[email protected]}</td>
<td>{[email protected]}</td>
<td>{$k}</td>
<td>{$v}</td>
<td>{[email protected]}</td>
</tr>
{/foreach}
</table>
数组中是否有元素:{[email protected]} <br>
数组中元素个数:{[email protected]}<br>
运行结果:
{section},{sectionelse}:遍历数组
只能遍历索引数组,不支持关联数组,因为{section}循环不能遍历数组的键,如果要用此循环遍历关联数组,必须自己指定键。
语法
{section name=自定义变量 loop=遍历数组}
{$数组名[变量名]}
{sectionelse}
没有数组被循环遍历
{/section}
{section}循环的属性
.first:是否是第一个元素
.index:索引号
.iteration:编号
.last:是否是最后一个元素
例题:
PHP代码:
require ‘./Smarty/Smarty.class.php’;
$smarty=new Smarty(); //实例化
$smarty->assign(‘stu’,array(‘tom’,’berry’,’ketty’,’rose’));
$smarty->display(‘demo14.html’);
HTML代码:
{include}:包含文件
原理
创建包含文件的头部
创建包含文件的脚
包含文件
{config_load}:导入配置文件
上面已经讲过,用于配置文件导入
{extends}和{block}:布局文件
原理
实现
- 创建template.html布局文件
- 在模板页面中继承布局文件,并替换
{nocache}、{literal}
后面专门讲解。
自定义函数
{html_checkboxes}:用来做表单元素的复选框
{html_radios} :单选按钮
{html_options}:下拉列表
语法和单选一样
PHP代码
<?php
require ‘./Smarty/Smarty.class.php’;
$smarty=new Smarty(); //实例化
$smarty->assign(‘output’,array(‘爬山’,’读书’,’游泳’,’看报’));
$smarty->assign(‘values’,array(‘a’,’b’,’c’,’d’));
$smarty->assign(‘selected’,array(‘b’,’d’));
$smarty->assign(‘options’,array(‘a’=>’爬山’,’b’=>’读书’,’c’=>’游泳’,’d’=>’看报’));
$smarty->display(‘demo17.html’);
HTML代码
{html_select_date}:显示日期
field_order:显示各下拉框的顺序
start_year:开始年份
month_format:格式化月份
{html_select_time}:显示时间
{cycle}:交替循环一系列值
<style type=”text/css”>
.aa{
color:#FF0000
}
.bb{
color:#009900
}
.cc{
color:#0000FF
}
</style>
<ul>
{foreach $output as $o}
<li class='{cycle values=”aa,bb,cc”}’>{$o}</li>
{/foreach}
</ul>
运行结果:
配置Smarty的路径常量
如果Smarty.class.php保存的路径很长,可以将目录定义成路径常量。
缓存
缓存的种类
- 页面缓存:页面的静态化
- 数据缓存:把MySQL数据库中的数据读取出来保存到更快的介质上。
开启缓存
Smarty中开启缓存开启的是页面缓存
语法:$smarty->caching=1 开启缓存
缓存文件的更改
- 删除对应的缓存文件,系统会自动更新
- 超过缓存的有效时间,会自动更新
- 更改对应的模板,配置文件,布局文件,包含文件,缓存会自动更新
- 强制重新生成缓存
$smarty->force_cache=true; //强制生成缓存
缓存的生命周期
$smarty->cache_lifetime=-1|0|N;
-1:缓存永远不失效
0:缓存立即失效
N:N秒以后失效
默认情况下,缓存是3600秒
例题
<?php
require ‘./Smarty/Smarty.class.php’;
$smarty=new Smarty(); //实例化
$smarty->caching=1; //开启缓存
//$smarty->force_cache=true; //强制生成缓存
$smarty->cache_lifetime=3;
$smarty->display(‘demo19.html’);
一个模板生成多个缓存
这是在分页的情况下使用,在display()方法中添加识别码就可以了
模板页面
PHP页面
缓存集合
每个组合都缓存一个静态页面
PHP代码
HTML代码
清除缓存
1、$smarty->clearCache(‘demo21.html’):清除demo21模板生成的所有缓存
2、$smarty->clearCache(‘demo21.html’,’vovo|green’):清除demo21生成的由vovo|green组合的缓存
3、$smarty->clearCache(‘demo21.html’,’vovo’):清除demo21生成的带有vovo的缓存
4、$smarty->clearCache(null,’vovo’):清除带有vovo的缓存。
5、$smarty->clearAllCache():清除所有缓存
局部不缓存
方法一:{变量 nocache},用于一个变量不缓存
方法二:{nocache} {/nocache},用于大块区域不缓存
解决js、css中的大括号和Smarty中大括号冲突
解决
方法一:更改smarty的定界符
方法二:
方法三:{literal}{/literal}
Smarty的常用方法
- setTemplateDir():设置模板文件夹
- setCompileDir():设置混编文件夹
- setCacheDir():设置缓存文件夹
- setConfigDir():设置配置文件夹
- assign() – 赋值
- display() – 显示
- clearCache() – 清除缓存
- clearAllCache() – 清除全部缓存
Smarty的常用属性
- $smarty->caching=1: //开启缓存
- $smarty->force_cache=true; //强制生成缓存
- $smarty->cache_lifetime=3; //缓存的生命周期
将Smarty集成到框架中
在上一讲的项目中,表现和内容没有分离,我们通过smarty将表现和内容相分离
- 将Smarty的核心目录拷贝Framework/Core目录下,改名为Smarty
- 更改Framework类中自动加载类,加载Smarty类
- 创建保存混编文件的目录
- 定义混编文件目录的路径常量
- 在基础控制器中初始化smarty
- 在ProductsController类中使用smarty对象
- 在products_list.html通过smarty循环取出数据
运行结果如下:
- 能够理解模板技术的含义和原理
- 能够引入并配置Smarty
- 能够使用Smarty完成视图的基本展示
- 能够使用模板中的三种变量
- 能够理解变量调节器的含义并使用3-5个
- 能够理解内建函数的含义并使用3-5个
- 能够创建自定义函数并调用之
- 能够配置Smarty的路径常量
- 能够配置Smarty的常用属性
- 能够使用Smarty的常用方法
- 能够创建并使用配置文件