語法基本形式
{$var|modifier1|modifier2:param1:param2|modifier3}
- 管線符 `
|` 串聯多個修飾器,左到右執行
- 參數用冒號 `
:` 分隔,字串參數建議加引號
25+ 內建修飾器分類速查
大小寫轉換
| 修飾器 | 功能 | 範例 | 結果 |
| lower | 全小寫 | {$name|lower} | john |
| upper | 全大寫 | {$name|upper} | JOHN |
| capitalize | 單字首字大寫 | {$title|capitalize} | Hello World |
| capitalize:true | 含數字單字也大寫 | {$code|capitalize:true} | Php7 → Php7 |
字串截取與長度
| 修飾器 | 功能 | 參數 | 範例 |
| truncate | 截斷並加尾碼 | 長度, 尾碼, 斷詞 | {$text|truncate:30:"..."} |
| strip | 壓縮空白/換行 | 替代字串 | {$text|strip:" "} |
| strip_tags | 移除 HTML 標籤 | 允許標籤 | {$html|strip_tags:""} |
| count_characters | 計算字元數 | 含空白 | {$str|count_characters:true} |
| count_words | 計算單字數 | — | {$str|count_words} |
| count_sentences | 計算句子數 | — | {$str|count_sentences} |
| count_paragraphs | 計算段落數 | — | {$str|count_paragraphs} |
字串搜尋替換
| 修飾器 | 功能 | 參數 | 範例 |
| replace | 簡單字串替換 | 搜尋, 替換 | {$str|replace:"old":"new"} |
| regex_replace | 正則替換 | 模式, 替換 | {$str|regex_replace:"/\d+/":"#"} |
編碼與格式化
| 修飾器 | 功能 | 參數 | 範例 |
| escape | HTML/URL/JS/HEX 編碼 | html|url|javascript|hex | {$var|escape:'html'} |
| date_format | 日期格式化 | strftime 格式, 預設時間 | {$time|date_format:"%Y-%m-%d"} |
| string_format | sprintf 格式化 | 格式字串 | {$price|string_format:"%.2f"} |
| nl2br | 換行轉 <br> | — | {$text|nl2br} |
| spacify | 字元間插入字串 | 插入字串 | {$str|spacify:"-"} |
| indent | 每行縮排 | 字元數, 字元 | {$block|indent:4:"\t"} |
| cat | 尾部連接字串 | 字串 | {$str|cat:" suffix"} |
預設值
{$title|default:"無標題"} {* 變數為空/未指派時顯示預設 *}
自訂修飾器開發
- 建立
plugins/modifier.修飾器名.php
- 函式命名:
smarty_modifier_修飾器名($string, $param1, ...)
- 回傳處理後字串
// plugins/modifier.reverse.php
function smarty_modifier_reverse($string) {
return strrev($string);
}
// 模板使用
{$text|reverse} {* 反轉字串 *}
效能建議
- 避免在迴圈內對大字串串聯多個複雜修飾器
- PHP 端預處理後再
assign() 給模板
- 編譯後模板為 PHP 程式碼,修飾器實際為函式呼叫,開銷極低
相關專題
- 《Smarty 模板入門基礎教程》
- 《PHP 模板技術總結》