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

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