smarty模板是一個(gè)使用PHP寫出來的模板引擎,是目前業(yè)界最著名的PHP模板引擎之一。它分離了邏輯代碼和外在的內(nèi)容,提供了一種易于管理和使用的方法,用來將原本與HTML代碼混雜在一起PHP代碼邏輯分離。簡(jiǎn)單的講,目的就是要使PHP程序員同前端人員分離,使程序員改變程序的邏輯內(nèi)容不會(huì)影響到前端人員的頁(yè)面設(shè)計(jì),前端人員重新修改頁(yè)面不會(huì)影響到程序的程序邏輯,這在多人合作的項(xiàng)目中顯的尤為重要。
一. 安裝
下載最新版本的Smarty。解壓下載的文件(目錄結(jié)構(gòu)還蠻復(fù)雜的)。接下來演示給大家一個(gè)安裝實(shí)例,看過應(yīng)該會(huì)舉一反三的。
(1) 在根目錄下建立了新的目錄learn/,再在learn/里建立一個(gè)目錄smarty/。將剛才解壓縮出來的目錄的libs/拷貝到smarty/里,再在smarty/里新建templates目錄,templates里新建cache/,templates/,templates_c/, config/。
(2) 新建一個(gè)模板文件:index.tpl,將此文件放在learn/smarty/templates/templates目錄下,代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"此處DOCTYPE
聲明不全,下午糾結(jié)了好一會(huì),終于看到了,新手朋友們關(guān)注下">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=gb2312">
<title>Smarty</title></head>
<body>{#$hello#}</body>
</html>
新建index.php,將此文件放在learn/下:
<?php
require 'smarty/libs/Smarty.class.php';
$smarty = new Smarty();//設(shè)置各個(gè)目錄的路徑,這里是安裝的重點(diǎn)
$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模板有高速緩存的功能,如果這里是true的話即打開caching,但是會(huì)造成網(wǎng)頁(yè)不立即更新的問題,當(dāng)然也可以通過其他的辦法解決
$smarty->caching = false;
$smarty->left_delimiter = "{#"; //重新定義邊界,因?yàn)槟J(rèn)邊界“{}“符,在html頁(yè)面中嵌入js腳本文件編寫代碼段時(shí)使用的就是”{}“符,自定義邊界符還可以是<{ }>, {/ /} 等
$smarty->right_delimiter = "#}";
$hello = "Hello World!";//賦值
$smarty->assign("hello",$hello);//引用模板文件
$smarty->display('index.tpl');?>
(3) 執(zhí)行index.php就能看到Hello World!了。
二. 賦值
在模板文件中需要替換的值用大括號(hào){}括起來,值的前面還要加$號(hào)。例如{$hello}。這里可以是數(shù)組,比如{$hello.item1},{$hello.item2}…
而PHP源文件中只需要一個(gè)簡(jiǎn)單的函數(shù)assign(var , value)。
簡(jiǎn)單的例子:
*.tpl:
*.php:
$hello[name]= “Mr. Green”;
$hello[time]=”morning”;
$smarty->assign(“exp”,$hello);
output:
Hello,Mr.Green!Good morning
三. 引用
網(wǎng)站中的網(wǎng)頁(yè)一般header和footer是可以共用的,所以只要在每個(gè)tpl中引用它們就可以了。
示例:*.tpl:
{include file="header.tpl"}
{* body of template goes here *}
{include file="footer.tpl"}