Smart模版
smarty是一個基於PHP開發的PHP模板引擎。它提供了邏輯與外在內容的分離,簡單的講,目的就是要使PHP程序員同美工分離,使用的程序員改變程序的邏輯內容不會影響到美工的頁面設計,美工重新修改頁面不會影響到程序的程序邏輯。
美工人員
1. 寫模板, HTML CSS JavaScript
2. 使用Smarty表現邏輯 放變量, 遍歷和判斷數據
PHP程序員
1. PHP程序和原來一樣(連接數據, 圖,文件)
2. 加載Smarty引擎, 並創建對象
3. 向引擎中分配變量(分數據)
4. 顯示那個模板
一、基本語法
定界符:建議修改定界符,以防模版中出現內部樣式造成混淆
<!--外部樣式-->
<link rel="stylesheet" type="text/css" href="css/mystyle.css"/>
<!--內部樣式-->
<style type="text/css">
p{
color: crimson;
}
</style>
</head>
<body>
<!--內聯樣式-->
<a href="http://www.baidu.com" style="color:blue;" target="_blank">百度:http://www.baidu.com</a>
$tpl->left_delimiter="<{"; //左定界符
$tpl->right_delimiter="}>"; //右定界符
注釋:在定界符中以兩個星號“*”進行注釋,如:<{* 注釋 *}>
二、Smart變量
1、來自PHP頁面中的變量 【調用從PHP分配的變量需在前加"$"符號,調用模板內的assign函數分配的變量也需要加"$"】
index.php: $smarty = new Smarty;
$smarty->assign('firstname', 'Doug'); //assign:注冊函數,將變量注冊 $smarty->assign('lastLoginDate', 'January 11th, 2001'); $smarty->display('index.tpl'); //合成模版文件 index.tpl: Hello {$firstname}, glad to see you could make it. Your last login was on {$lastLoginDate}.
1.1 讀取關聯數組,需要使用"."符號連接
index.php: $smarty = new Smarty; $smarty->assign('Contacts',array('fax' => '555-222-9876','email' => 'zaphod@slartibartfast.com','phone' => array('home' => '555-444-3333','cell' => '555-111-1234')));
$smarty->display('index.tpl'); index.tpl: {$Contacts.fax}<br> {$Contacts.email}<br> {* 打印二維關聯數組 *} {$Contacts.phone.home}<br> {$Contacts.phone.cell}<br>
1.2 讀取索引數組
index.php: $smarty = new Smarty; $smarty->assign('Contacts',array('555-222-9876','zaphod@slartibartfast.com',array('555-444-3333','555-111-1234'))); $smarty->display('index.tpl'); index.tpl: <{$Contacts[0]}><br> <{$Contacts[1]}><br> {* 二維索引 *} <{$Contacts[2][0]}><br> <{$Contacts[2][1]}><br>
1.3 對象引用
name: <{$person->name}><br>
email: <{$person->email}><br>
2、從配置文件讀取變量
要使用 $tpl->configs_dir="configs" //指定配置文件存放的目錄
在模板.tpl中要使用 <{configs_load file="view.conf"}> 加載view.conf配置文件
配置文件中的變量需要通過用兩個"#"或者是smarty的保留變量 $smarty.config.~來調用
foo.conf: pageTitle = "This is mine" bodyBgColor = "#eeeeee" tableBorderSize = "3" tableBgColor = "#bbbbbb" rowBgColor = "#cccccc" index.tpl: {config_load file="foo.conf"} <html> <title><{#pageTitle#}></title> <body bgcolor="<{#bodyBgColor#}>"> <table border="<{#tableBorderSize#}>" bgcolor="<{#tableBgColor#}>"> <tr bgcolor="<{#rowBgColor#}>"> index.tpl: ($smarty.config.~) {config_load file="foo.conf"} <html> <title><{$smarty.config.pageTitle}></title> <body bgcolor="<{$smarty.config.bodyBgColor}>"> <table border="<{$smarty.config.tableBorderSize}>" bgcolor="<{$smarty.config.tableBgColor}>"> <tr bgcolor="<{$smarty.config.rowBgColor}>">
3、保留變量
{$smarty}保留變量可以被用於訪問一些特殊的模板變量.如:get、post、server、session、cookie、request、now、const、config
例:get:<{$smarty.get.page}> $_GET now:<{$smarty.now}> 當前時間戳
三、變量調節器
變量調節器用於變量,自定義函數和字符串。使用‘|’符號和調節器名稱應用調節器。變量調節器由賦予的參數值決定其行為。參數由‘:’符號分開。
index.php: $smarty = new Smarty; $smarty->assign('yesterday', strtotime('-1 day')); $smarty->display('index.tpl'); index.tpl: {$smarty.now|date_format} {$smarty.now|date_format:"%A, %B %e, %Y"} {$smarty.now|date_format:"%H:%M:%S"} {$yesterday|date_format} {$yesterday|date_format:"%A, %B %e, %Y"} {$yesterday|date_format:"%H:%M:%S"}
index.php: $smarty = new Smarty; $smarty->assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.'); $smarty->display('index.tpl'); index.tpl: {$articleTitle} {$articleTitle|truncate} {$articleTitle|truncate:30} {$articleTitle|truncate:30:""} {$articleTitle|truncate:30:"---"} {$articleTitle|truncate:30:"":true} {$articleTitle|truncate:30:"...":true} OUTPUT: Two Sisters Reunite after Eighteen Years at Checkout Counter. Two Sisters Reunite after Eighteen Years at Checkout Counter. Two Sisters Reunite after... Two Sisters Reunite after Two Sisters Reunite after--- Two Sisters Reunite after Eigh Two Sisters Reunite after E...
注:truncate變量可能在截取中英文頁面時出現亂碼,可通過自定義一個函數,將其注冊(register_function/register_block)或定義在插件庫modifier.~,來進行調用【如:按utf-8截取的算法】
四、組合修改器分隔多個變量調節器
對於同一個變量,你可以使用多個修改器。它們將從左到右按照設定好的順序被依次組合使用。使用時必須要用"|"字符作為它們之間的分隔符。
index.php: $smarty = new Smarty; $smarty->assign('articleTitle', 'Smokers are Productive, but Death Cuts Efficiency.'); $smarty->display('index.tpl'); index.tpl: {$articleTitle} {$articleTitle|upper|spacify} {$articleTitle|lower|spacify|truncate} {$articleTitle|lower|truncate:30|spacify} {$articleTitle|lower|spacify|truncate:30:". . ."}
五、自定義函數
Smarty 自帶的一組自定義函數,用戶可根據實際需求進行修改、增加或刪除
{counter start=0 skip=2 print=false}
{counter}<br>
{counter}<br>
{counter}<br>
{counter}<br>
{math equation="x + y" x=$height y=$width}
OUTPUT:
9
用戶可根據需求自定函數:
1、注冊函數或塊
$smarty->register_function("date_now", "print_current_date"); function print_current_date ($params) { extract($params); if(empty($format)) $format="%b %e, %Y"; return strftime($format,time());}
$smarty->register_block("translate", "do_translation"); function do_translation ($params, $content, &$smarty, &$repeat) { if (isset($content)) { $lang = $params['lang']; // do some translation with $content return $translation; }} {* template *}{translate lang="br"} Hello, world!{/translate}
register_block (string name, mixed impl, bool cacheable, array or null cache_attrs)
2、插件庫
接口規則:命名:以funcition.~開頭是函數;以block.~開頭是塊;以modifier.~過濾函數;
函數名:function smarty_block_world($args, $content, &$smarty) function smarty_function_math($params, &$smarty)
&$smarty:必須加上去,可換名字,但需有這參數引用
六、內建函數
Smarty自帶一些內建函數. 內建函數是模板語言的一部分. 用戶不能創建名稱和內建函數一樣的自定義函數,也不能修改內建函數.
{* 該例在捕獲到內容后輸出一行包含數據的表格,如果沒有捕獲到就什么也不輸出 *}
{capture name=banner}
{include file="get_banner.tpl"}
{/capture}
{if $smarty.capture.banner ne ""}
<tr>
<td>
{$smarty.capture.banner}
</td>
</tr>
{/if}
foreach與PHP的foreach用法相同,關聯數組
{if $name eq "Fred"}
Welcome Sir.
{elseif $name eq "Wilma"}
Welcome Ma'am.
{else}
Welcome, whatever you are.
{/if}
{* an example with "or" logic *}
{if $name eq "Fred" or $name eq "Wilma"}
...
{/if}
{* same as above *}
{if $name == "Fred" || $name == "Wilma"}
...
{/if}
{* the following syntax will NOT work, conditional qualifiers
must be separated from surrounding elements by spaces *}
{if $name=="Fred" || $name=="Wilma"}
...
{/if}
{* parenthesis are allowed *}
{if ( $amount < 0 or $amount > 1000 ) and $volume >= #minVolAmt#}
...
{/if}
{* you can also embed php function calls *}
{if count($var) gt 0}
...
{/if}
{* test if values are even or odd *}
{if $var is even}
...
{/if}
{if $var is odd}
...
{/if}
{if $var is not odd}
...
{/if}
{* test if var is divisible by 4 *}
{if $var is div by 4}
...
{/if}
{* test if var is even, grouped by two. i.e.,
0=even, 1=even, 2=odd, 3=odd, 4=even, 5=even, etc. *}
{if $var is even by 2}
...
{/if}
{* 0=even, 1=even, 2=even, 3=odd, 4=odd, 5=odd, etc. *}
{if $var is even by 3}
...
{/if}
section 用於遍歷數組中的數據.
section 標簽必須成對出現. 必須設置
name 和
loop 屬性. 名稱可以是包含字母、數字和下划線的任意組合. 可以嵌套但必須保證嵌套的 name 唯一. 變量 loop (通常是數組)決定循環執行的次數. 當需要在 section 循環內輸出變量時,必須在變量后加上中括號包含着的 name 變量.
<table align="center" width="800" border="1">
<{section loop=$data name="ls" start="10" step="3" max="10"}>
<tr>
<td><{$smarty.section.ls.index}></td>
<td><{$smarty.section.ls.rownum}></td>
<td><{$data[ls].id}></td>
<td><{$data[ls].name}></td>
<td><{$data[ls].price}></td>
<td><{$data[ls].num}></td>
<td><{$data[ls].desn}></td>
<td><{$data[ls].sub}></td>
<td>
<{section loop=$data[ls].sub name="lsin"}>
##<{$data[ls].sub[lsin].one}><br>
<{/section}>
</td>
</tr>
<{sectionelse}>
數組中沒有數據
<{/section}>
</table>
注:建議使用section進行數組遍歷,因為其效率比foreach更高,而且功能多;但遍歷數組時下標必須連續
七、緩存
Smarty緩存和網頁表態化一樣, 使用Smarty緩存使用非常方便
1. 需要開啟緩存
2. 指定一下緩存的時間
3. 指定緩存文件保存位置
$tpl->caching=1; //開啟緩存【在開發階段不要開,運行階段再開啟】 $tpl->cache_dir=ROOT."cache"; //緩存文件 $tpl->cache_lifetime=10; //緩存文件生存時間
注意:
1. 一個模板只能有一個緩存文件,如果一個模板的多個文章,則需要每個文章有一個
緩存
$tpl->display("test.tpl", cacheid);
第二個參數,每變化一個值就會有一個不同的緩存(最好使用$_SERVER["REQUEST_URI"])針對每條URL進行緩存,防止出現重復的緩存文件
2. 一定要處理,如果有緩存了就不要執行連接數據庫和到數據庫中操作數據表了。
使用smarty中的is_cached()方法去判斷,它的用法和display()相同
if(!$tpl->is_cached("test.tpl",$_SERVER["REQUEST_URI"])){ $mysqli=new mysqli("localhost", "root", "123456", "database"); $result=$mysqli->query("select id from shops");
局部緩存設置
使用一個塊標記完成,register_block("nocache", "nocache", false)
function smarty_block_nocache($params, $content, &$s){ return $content;
test.tpl
<caption><h1>SHOPS<{nocache}><{$date}><{/nocache}></h1></caption>
<tr>
<{nocache}>
插件庫:block.nocache.php,並修改文件Smarty_Compiler.class.php 712行
if (!function_exists($plugin_func)) { $message = "plugin function $plugin_func() not found in $plugin_file\n"; $have_function = false; } else { if($tag_command=="nocache") $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, false); else $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true); }
清除緩存功能
$tpl->clear_all_cache(); //清除所有緩存
clear_cache() 清除指定緩存
Smarty使用注意事項
1. 因為我們訪問是PHP文件,而模板是在PHP中包含的內容,所以在模板中使用 圖片,CSS文件,js文件,都要以訪問的PHP目錄為主
2. 所有display模板時(還是模板中include),都要以Smarty對象中指定的模板目錄為基目錄
3. 如果想讓各個目錄下的PHP程序都可以加載Smarty和使用Smarty指定的模板和編譯目錄,唯一的辦法就是使用絕對路徑。
