2012-11-15
概念:
为了处理同样的显示界面,不同的显示内容。内容有url参数决定
。同一个模板可以生成多个缓存文件(有多少中内容显示就有多少个缓存
文件),多个缓存缓存文件用display("*tpl",$_GET["id"]);在PHP中可
以用is_cached判断模板是否被缓存,is_cached格式和display完全一样
。
做的实例:
init.inc.php文件
<?php
include "libs/Smarty.class.php";
$smarty=new Smarty();
$smarty->template_dir="demo/templates";
$smarty->compile_dir="demo/templates_c";
$smarty->config_dir="demo/config";
$smarty->cache_dir="demo/cache";
?>
-----------------------------------------------------
Stu.php文件
<?php
include "init.inc.php";
$smarty->caching=1;
if(!$smarty->is_cached("Stu2.tpl")){
mysql_connect('localhost','root','123') or die('连接数据库失败!');
mysql_select_db('xx');
mysql_query("set names utf8");
$q=mysql_query("select * from stu");
$arrqy=array();
$i=0;
while($row=mysql_fetch_assoc($q)){
$array[$i]=$row;
$i++;
}
//var_dump($array);
$smarty->assign('array',$array);}
$smarty->display("Stu.tpl");
?>
---------------------------------------------
Stu.tpl文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>各学生详细信息</title>
</head>
<body>
<table border="1">
<tr><th>学号</th><th>姓名</th><th>出生日期</th></tr>
<{section name=stu loop=$array}>
<tr>
<td><{$array[stu].id}></td>
<td><{$array[stu].name}></td>
<td><{$array[stu].birthday}></td>
<td><a href="Stu2.php?id=<{$array[stu].id}>">详细信息</a></td>
</tr>
<{/section}>
</table>
</body>
</html>
---------------------------------------------------------------
Stu2.php文件
<?php
include "init.inc.php";
$smarty->caching=1;
if(!$smarty->is_cached("Stu2.tpl")){
mysql_connect('localhost','root','123') or die('连接数据库失败!');
mysql_select_db('xx');
mysql_query("set names utf8");
$q=mysql_query('select * from stu where id='.$_GET['id']);
$array=array();
$i=0;
while($row=mysql_fetch_assoc($q)){
$array[$i]=$row;
$i++;
}
//$smarty->assign('arr',$array);
$smarty->assign("a",$array);
echo "没有缓存设置、";
}
$smarty->display("Stu2.tpl");
?>
-------------------------------------------------------------
Stu2.tpl文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><{section name='cao' loop=$a}>
<{$a[cao].name}>的详细信息<{/section}>
</title>
</head>
<body>
<{section name='cao' loop=$a}>
学号:<{$a[cao].id}><br />
姓名:<{$a[cao].name}><br />
生日:<{$a[cao].birthday}><br />
<{/section}>
<a href="Stu.php">返回首页</a>
</body>
</html>