truncate 基本語法
{$var|truncate[:length[:etc[:break_words[:middle]]]]}
- length:截取長度(預設 80),包含
etc 字串長度
- etc:尾部附加字串(預設
...)
- break_words:
true 強制在指定長度截斷(可能斷詞),false 於詞邊界截斷(預設)
- middle:
true 從中間截斷(兩端保留),false 從尾部截斷(預設)
實際範例
<?php
// index.php
$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.');
$smarty->display('index.tpl');
?>
{* index.tpl *}
{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}
輸出結果對照
| 範本語法 | 輸出結果 | 說明 |
{$articleTitle} | Two Sisters Reunite after Eighteen Years at Checkout Counter. | 原文 |
{$articleTitle|truncate} | Two Sisters Reunite after Eighteen Years at Checkout Counter. | 未超過 80 字,不截斷 |
{$articleTitle|truncate:30} | Two Sisters Reunite after... | 詞邊界截斷 + 預設 ... |
{$articleTitle|truncate:30:""} | Two Sisters Reunite after | 無尾碼,詞邊界 |
{$articleTitle|truncate:30:"---"} | Two Sisters Reunite after--- | 自訂尾碼 --- |
{$articleTitle|truncate:30:"":true} | Two Sisters Reunite after Eigh | 強制 30 字截斷(斷詞) |
{$articleTitle|truncate:30:"...":true} | Two Sisters Reunite after E... | 強制截斷 + 尾碼 ... |
進階技巧
- 中文環境:預設按字元計算,中文無空格分詞,建議搭配
break_words=true 或使用 mb_truncate 自訂修飾器。
- 中間截斷:
{$longUrl|truncate:50:"...":false:true} 保留開頭網域與結尾檔名,中間用 ... 取代。
- 搭配其他修飾器:
{$text|strip_tags|truncate:100:"..."} 先移除 HTML 標籤再截斷。
常見誤區
- 以為
length 不含 etc 長度 —— 實際包含在內。
- 以為預設會在單字中間斷開 —— 實際預設尋找空格,只有加
true 才強制斷詞。
- 以為
truncate 支援 HTML 感知截斷 —— 不支援,會破壞標籤結構,需先 strip_tags。