smarty模板是一(yī)个使用PHP写出来的模板引擎(qíng),是目前业(yè)界(jiè)最著名的PHP模板引擎之(zhī)一。它分离(lí)了逻辑代码和外在的内容,提供(gòng)了一种易于(yú)管理和使用的方法,用来(lái)将原本与(yǔ)HTML代码混杂在一(yī)起PHP代码逻辑分离。简单的(de)讲,目的就是(shì)要使PHP程序员同前端人员分离,使程序(xù)员改(gǎi)变程序(xù)的逻辑内容不会影响到前端人员的页面设计,前端人员重新修改(gǎi)页(yè)面(miàn)不会影响到程序的程序逻辑,这在多人合作(zuò)的项目中(zhōng)显的尤(yóu)为重(chóng)要。

一. 安装
下载(zǎi)最新版本的Smarty。解(jiě)压下载(zǎi)的(de)文件(目录结构还蛮复杂的)。接下来演示给大家一个安(ān)装实例,看过应该会举一反三(sān)的(de)。
(1) 在(zài)根目录下建立了新(xīn)的目录learn/,再在learn/里建立一个目录smarty/。将刚才解(jiě)压缩出来(lái)的目录的(de)libs/拷贝到smarty/里,再在smarty/里新建templates目(mù)录,templates里新(xīn)建cache/,templates/,templates_c/, config/。
(2) 新建一个(gè)模(mó)板文件:index.tpl,将此文件放在(zài)learn/smarty/templates/templates目录下,代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"此处DOCTYPE
声明不全,下午纠结(jié)了好一会,终于看到(dào)了,新手朋友们关注下">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Smarty</title></head>
<body>{#$hello#}</body>
</html>
新(xīn)建(jiàn)index.php,将此文件放(fàng)在learn/下:
<?php
require 'smarty/libs/Smarty.class.php';
$smarty = new Smarty();//设置各(gè)个目(mù)录的路径(jìng),这里(lǐ)是安装的(de)重点
$smarty->template_dir ="smarty/templates/templates";
$smarty->compile_dir ="smarty/templates/templates_c";
$smarty->config_dir = "smarty/templates/config";
$smarty->cache_dir ="smarty/templates/cache";
//smarty模板有高(gāo)速缓(huǎn)存的功能,如果(guǒ)这(zhè)里是true的话即打开caching,但(dàn)是会造成(chéng)网页不(bú)立即更新(xīn)的问题(tí),当然也(yě)可以通过其他的办法解决
$smarty->caching = false;
$smarty->left_delimiter = "{#"; //重新定义边界,因为默认边界(jiè)“{}“符,在html页面中嵌入js脚本文件(jiàn)编写(xiě)代(dài)码段时使用的就(jiù)是”{}“符,自定义(yì)边界(jiè)符还可以是<{ }>, {/ /} 等
$smarty->right_delimiter = "#}";
$hello = "Hello World!";//赋值
$smarty->assign("hello",$hello);//引用模(mó)板文件
$smarty->display('index.tpl');?>
(3) 执(zhí)行index.php就能看到(dào)Hello World!了(le)。
二(èr). 赋值
在模板文(wén)件中需要替换(huàn)的值用大括号{}括起来,值的前面还(hái)要加$号。例如{$hello}。这里可以是数组,比如(rú){$hello.item1},{$hello.item2}…
而PHP源文(wén)件中只(zhī)需(xū)要一个简单的函数(shù)assign(var , value)。
简单的例(lì)子(zǐ):
*.tpl:
*.php:
$hello[name]= “Mr. Green”;
$hello[time]=”morning”;
$smarty->assign(“exp”,$hello);
output:
Hello,Mr.Green!Good morning
三. 引用
网站中的网页一般header和footer是可以共用的,所以只要在每个tpl中(zhōng)引(yǐn)用它们就可以(yǐ)了。
示例:*.tpl:
{include file="header.tpl"}
{* body of template goes here *}
{include file="footer.tpl"}