系統整理 Smarty 內建變數修飾器,涵蓋字串操作、HTML 處理、日期格式化、數字格式化、陣列操作等 20+ 種修飾器,並提供完整 PHP 指派資料與模板輸出對照範例,作為開發時的快速查閱手冊。
PHP 端:測試資料準備
<?php
require_once('libs/Smarty.class.php');
$smarty = new Smarty();
$smarty->assign('name', ['na1' => '帥哥', 'na2' => '美女']);
$smarty->assign('str', '帥哥');
$smarty->assign('str1', "<a href='https://www.sina.com/'>新浪</a> And\n aassu@163.com");
$smarty->assign('str2', 'aassu@163.com');
$smarty->assign('number', 30.293934);
$smarty->assign('str3', "akie abfal <a;fa>,dooerw,show databases,desc table");
$smarty->assign('config', 'Y-m-d H:i:s');
$smarty->assign('yesterday', strtotime('-1 day'));
define('MY_CONST', '百度');
class Dog { public $name; public function leee() { return $this->name . '在幹嘛'; } }
$dog = new Dog(); $dog->name = '小狗'; $smarty->assign('dog', $dog);
$family = ['husband' => '帥哥', 'wife' => '美女'];
$famiadd = ['boy' => '張三豐', 'girl' => '王昭君'];
$smarty->append('family', $family);
$smarty->append('family', $famiadd);
$smarty->display('temp.htm');
?>
核心修飾器分類速查
字串連接與輸出
| 修飾器 | 功能 | 範例 | 輸出 |
cat | 字串連接 | {$name.na1|cat:$name.na2} | 帥哥美女 |
cat 多重 | 鏈式連接 | {$name.na1|cat:'與'|cat:$name.na2} | 帥哥與美女 |
HTML/編碼處理
| 修飾器 | 功能 | 範例 |
escape:'html' | HTML 實體編碼 | {$str1|escape:'html'} → 顯示原始標籤 |
escape:'mail' | Email 地址編碼(防採集) | {$str2|escape:'mail'} |
escape:'url' | URL 編碼 | {$url|escape:'url'} |
strip_tags | 移除 HTML 標籤 | {$str3|strip_tags} |
日期時間格式化
| 修飾器 | 功能 | 範例 |
date_format:'%Y-%m-%d' | Unix 時間戳格式化 | {$smarty.now|date_format:$config} |
date_format:'%Y-%m-%d' | 字串時間解析+格式化 | {$yesterday|date_format:'%Y-%m-%d'} |
字串格式化與處理
| 修飾器 | 功能 | 範例 |
default:'預設值' | 變數為空時顯示預設值 | {$emptyVar|default:'N/A'} |
indent | 每行縮排 4 空格 | {$str1|indent} |
upper | 轉大寫 | {$str|upper} |
lower | 轉小寫 | {$str|lower} |
capitalize | 首字大寫 | {$str|capitalize} |
nl2br | 換行轉 <br> | {$str1|nl2br} |
regex_replace:'/pattern/':'replacement' | 正則替換 | {$str1|regex_replace:'/@\d{3}/':'ABC'} |
replace:'search':'replace' | 字串替換 | {$str1|replace:'163':'sina'} |
spacify | 字元間插入空格 | {$str|spacify} → 帥 哥 |
string_format:'%.2f' | 數字格式化 (sprintf) | {$number|string_format:'%.2f'} → 30.29 |
truncate:10:'...':true | 截斷字串 | {$str3|truncate:10:'...':true} |
wordwrap:30:'<br>' | 指定寬度換行 | {$str3|wordwrap:30:'<br>'} |
strip:'|' | 移除多餘空白,以字元連接 | {$str3|strip:'|'} |
陣列操作
| 修飾器/標籤 | 功能 | 範例 |
{append var='arr' value='v' index='k'} | 陣列追加元素 | {append var='name' value='Bob' index='first'} |
Smarty 保留變數
{$smarty.now} // 當前時間戳
{$smarty.const.MY_CONST} // PHP 常數
{$smarty.template} // 當前模板檔名
{$smarty.version} // Smarty 版本
{$smarty.ldelim} // 左分隔符 {
{$smarty.rdelim} // 右分隔符 }
實戰組合範例
{* 日期格式化 *}
{$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}
{* HTML 安全輸出 + 截斷 *}
{$article.content|strip_tags|truncate:200:'...'}
{* 郵件地址混淆 *}
{$user.email|escape:'mail'}
{* 貨幣格式化 *}
{$price|string_format:'%.2f'}
熟練運用修飾器,能在模板層完成大部分資料格式化需求,保持 PHP 邏輯層乾淨。