Smarty 修飾器(Modifier)以管道符 | 套用於變數,支援鏈式調用與參數傳遞。官方內建 20+ 修飾器,涵蓋字串處理、格式化、轉義、截斷等常見需求。本文逐一說明語法、參數與實戰範例。
| 修飾器 | 功能 | 參數說明 | 範例 |
|---|---|---|---|
| capitalize | 單詞首字大寫 | bool 是否處理含數字單詞(預設 false) | {$str|capitalize:true} |
| count_characters | 計算字元數 | bool 是否計算空白(預設 false) | {$str|count_characters:true} |
| cat | 字串連接 | string 尾部附加字串 | {$str|cat:' - 附註'} |
| count_paragraphs | 段落數(雙換行分隔) | - | {$text|count_paragraphs} |
| count_sentences | 句子數(英文句點判斷) | - | {$text|count_sentences} |
| count_words | 單詞數 | - | {$str|count_words} |
| date_format | 日期格式化 | string strftime 格式字串 | {$timestamp|date_format:'%Y-%m-%d %H:%M'} |
| default | 預設值(變數為空/未定義) | string 預設字串 | {$var|default:'無資料'} |
| escape | 編碼轉義 | html|url|quotes|hex|hexentity|javascript(預設 html) | {$url|escape:'url'} |
| indent | 每行縮排 | int 字元數(預設 4)、string 縮排字元(預設空格) | {$text|indent:2:'>'} |
| lower | 轉小寫 | - | {$str|lower} |
| upper | 轉大寫 | - | {$str|upper} |
| nl2br | 換行轉 <br> | - | {$text|nl2br} |
| regex_replace | 正則替換 | pattern, replacement(preg_replace 語法) | {$url|regex_replace:'/google/':'baidu'} |
| replace | 簡單字串替換 | search, replace | {$str|replace:'old':'new'} |
| spacify | 字元間插入分隔符 | string 分隔符(預設空格) | {$str|spacify:'^^'} |
| string_format | 格式化浮點數 | string sprintf 格式 | {$num|string_format:'%.2f'} |
| strip | 合併連續空白字元 | string 替換字元(預設空格) | {$text|strip:' '} |
| strip_tags | 移除 HTML 標籤 | - | {$html|strip_tags} |
| truncate | 截斷字串 | int 長度(預設 80)、string 尾碼(預設 ...)、bool 是否精確截斷單詞(預設 false) | {$long|truncate:50:'...':true} |
// PHP
$tpl->assign('now', time());
$tpl->assign('dt', '2024-01-15 14:30:00');
{$now|date_format:'%Y-%m-%d %H:%M:%S'} {* 2024-01-15 14:30:00 *}
{$dt|date_format:'%Y年%m月%d日'} {* 2024年01月15日 *}
{$html|escape:'html'} {* <a> -> <a> *}
{$url|escape:'url'} {* 空格 -> %20 *}
{$jsVar|escape:'javascript'} {* 換行 -> \n, 單引號 -> \' *}
{$article|truncate:100} {* 100 字元,單詞邊界截斷,加 ... *}
{$article|truncate:100:'...':true} {* 強制 100 字元精確截斷 *}
{$article|truncate:50:' [閱讀全文]'}
{* 隱藏手機中間 4 碼 *}
{$mobile|regex_replace:'/(\d{3})\d{4}(\d{4})/':'$1****$2'}
{* 移除多餘空白行 *}
{$content|regex_replace:'/\n{3,}/':"\n\n"}
{* 先截斷再轉義,防止 XSS *}
{$userInput|truncate:200:'...':true|escape:'html'}
{* 格式化價格:保留 2 位小數,加千分位 *}
{$price|string_format:'%.2f'|regex_replace:'/(\d)(?=(\d{3})+(?!\d))/':'$1,'}
參考 《Smarty 自定義修飾器開發指南》(對應 ID 57882)。