Smarty 變數修飾器(Modifiers)是模板開發的利器,能直接在模板中對變數進行格式化、轉換、截取等操作。本文整理常用修飾器用法,供開發查閱。
| 修飾器 | 功能 | 範例 |
|---|---|---|
capitalize | 首字母大寫 | {$name|capitalize} |
lower | 轉小寫 | {$name|lower} |
upper | 轉大寫 | {$name|upper} |
cat | 字串連接 | {$name|cat:'welcome'} 或 {$name|cat:$title} |
replace | 字串替換 | {$url|replace:'old.com':'new.com'} |
regex_replace | 正則替換 | {$text|regex_replace:'/pattern/':'replacement'} |
spacify | 字元間插入字串 | {$str|spacify:'^^'} |
strip | 移除多餘空白 | {$text|strip:' '} |
strip_tags | 移除 HTML 標籤 | {$content|strip_tags} |
truncate | 截取字串 | {$long_text|truncate:50:'...'} |
wordwrap | 強制換行 | {$text|wordwrap:80:"\n":true} |
indent | 首行縮排 | {$text|indent:10:' '} |
nl2br | 換行轉 <br> | {$text|nl2br} |
escape | 編碼轉義 | {$url|escape:'url'} |
| 修飾器 | 功能 | 範例 |
|---|---|---|
count_characters | 字元數 | {$text|count_characters} |
count_words | 單字數 | {$text|count_words} |
count_sentences | 句子數 | {$text|count_sentences} |
count_paragraphs | 段落數 | {$text|count_paragraphs} |
date_format - 格式化時間戳
{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}
// 輸出:2024-01-15 14:30:25
default - 變數為空時使用預設值
{$name|default:'Guest'}
string_format - 類似 PHP sprintf 格式化
{$price|string_format:"%.2f"}
修飾器可鏈式呼叫:{$var|modifier1|modifier2:arg},執行順序從左到右。複雜邏輯建議在 PHP 控制器預處理,保持模板簡潔。