Smarty模版技术
一、什么是Smarty?
1.概念:是使用PHP写出来的模板引擎,实现了后台逻辑(*.php)和外在内容(前台页面)分离,将php程序员和美工设计人员进行分离。
2.优点:在比较大的项目中才得以体现:当后台数据没有变化的时候,只需一次编译,只有当后台数据发生变化时,页面才需要重新编译。
3.不适合使用Smarty色地方:
(1)小项目(美工和后台程序一人就能实现)
(2)数据更新需要实时(eg:股市行情)
二、应用Smarty
1.引入Smarty.class.php文件
2.创建Smarty对象
3.更改模板存放路径及编译路径(templates_dir compile_dir)
4.修改界定符(left_delimiter right_delimiter)
5.编写模板(*.tpl(就是html)里面的数据部分用Smarty变量表示)
6.在php文件中用assign方法给模板中的变量赋值
7.在php文件中用display方法将模板及数据显示。
三、Smarty中的变量
1.模板中变量的声明
一般变量:<{$name}>
数组变量:索引数组和关联数组
索引数组:<{$arrName[row][col]}>
关联数组:<{$arrName.key1.key2}>
对象变量:<{$obj->att}>
<{$obj->fun()}>
2.给模板分配变量(通过php给模板中的变量赋值)
通过assign方法
四、实例
smarty.php文件
<?php
$address = array('北京','上海','河北');
$birthday = array("year"=>"1987","month"=>"8","day"=>"18");
include "libs/Smarty.class.php";
$smarty = new Smarty();
$smarty->templates_dir="demo/templates";
$smarty->compile_dir="demo/templates_c";
$smarty->left_delimiter="<{";
$smarty->right_delimiter="}>";
$smarty->assign("a",$address);
$smarty->assign("b",$birthday);
$smarty->display("test.tpl");
?>
test.tpl文件
<{include file="header.tpl"}>
<select>
<option>{<$a[0]>}</option>
<option>{<$a[1]>}</option>
<option>{<$a[2]>}</option>
</br>
<{$b.year}>年<{$b.month}>月<{$b.day}>日
</select>
<{include file="foot.tpl"}>