本文實例講述了Smarty變量用法。分享給大家供大家參考,具體如下:
1. 從PHP分配的變量
調用從PHP分配的變量需在前加"$"符號.(譯注:同php一樣)
調用模板內的assign函數分配的變量也是這樣.(譯注:也是用$加變量名來調用)
示例:
index.php:
$smarty = new Smarty;
$smarty->assign('firstname', 'Doug');
$smarty->assign('lastLoginDate', 'January11th, 2001');
$smarty->display('index.tpl');
index.tpl:
Hello {$firstname}, glad to see you couldmake it.
<p>
Your last login was on {$lastLoginDate}.
輸出:
Hello Doug, glad to see you could make it. <p> Your last login was on January 11th, 2001.
2. 從配置文件讀取的變量
配置文件中的變量需要通過用兩個"#"或者是smarty的保留變量 $smarty.config.來調用(後面會講到)
第二種語法在變量作為屬性值並被引號括住的時候非常有用.
(譯注:舉個例子 {include file="#includefile#"} 這樣#includefile#將被當作字符處理,而不表示配置文件變量,但可以這樣表示{include file="`$smarty.config.includefile`"}不要忘了加``)
示例:
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#}">
<td>First</td>
<td>Last</td>
<td>Address</td>
</tr>
</table>
</body>
</html>
index.tpl:
{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}">
<td>First</td>
<td>Last</td>
<td>Address</td>
</tr>
</table>
</body>
</html>
上述兩種模板寫法都輸出:
<html>
<title>This is mine</title>
<body bgcolor="#eeeeee">
<table border="3" bgcolor="#bbbbbb">
<tr bgcolor="#cccccc">
<td>First</td>
<td>Last</td>
<td>Address</td>
</tr>
</table>
</body>
</html>
配置文件的變量只有在它們被加載以後才能使用.
更多關於Smarty相關內容感興趣的讀者可查看本站專題:《smarty模板入門基礎教程》、《PHP模板技術總結》、《PHP基於pdo操作數據庫技巧總結》、《PHP運算與運算符用法總結》、《PHP網絡編程技巧總結》、《PHP基本語法入門教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家基於smarty模板的PHP程序設計有所幫助。