Smrty 模板的基本使用步骤
1. 配置smarty模板,将下载好的smarty模板中的 libs 库拷贝到工程目录下
2. 创建两个文件夹 ,存放模板文件的 templates 和存放模板文件编译后的文件templates_c
3. 在templates文件夹中创建模板 SmartyTest.tpl ,代码如下:
<html>
<head>
<title><{$title}></title>
<meta charset="utf-8"/>
</head>
<body style="background-color :<{$color}>">
<h1><{$contents}></h1>
</body>
</html>
其中$title,$color,$contents表示要替换的变量占位符
4. 创建 SmartyTest.php 文件,代码如下:
<?php
require_once './libs/SmartyBC.class.php';
//创建smarty对象
$smarty=new SmartyBC();
$smarty->left_delimiter="<{";
$smarty->right_delimiter="}>";
//设置缓存
$smarty->caching=true;//开启缓存
$smarty->cache_lifetime=60;//缓存的生命周期
$smarty->cache_dir="./caches";//存放缓存caches的文件夹
//分配变量
$smarty->assign("title","SmartyTest");
$smarty->assign("color","pink");
$smarty->assign("contents","This is a Smarty Test.");
$smarty->display("SmartyTest.tpl");
?>
引入smarty模板libs库中的SmartyBC.class.php类,并创建其对象;
left_delimiter,right_delimiter分别表示替换变量的左、右标识分隔符,包含在其内的内容表示要被替换的变量;
assign()函数:assign("被替换的变量名","变量值");[这里变量可以是基本数据类型、数组、对象]
display()函数:display("模板文件名");