truncate

Parameter PositionTypeRequiredDefaultDescription
1integerNo80This determines how many characters to truncate to.
2stringNo...This is the text to append if truncation occurs.
3booleanNofalseThis determines whether or not to truncate at a word boundary (false), or at the exact character (true).

This truncates a variable to a character length, default is 80. As an optional second parameter, you can specify a string of text to display at the end if the variable was truncated. The characters in the string are included with the original truncation length. By default, truncate will attempt to cut off at a word boundary. If you want to cut off at the exact character length, pass the optional third parameter of true.

此函式會截斷變數中某個長度後的資料,預設長度是80,如果你有使用第二個參數的 話,則可以指定在截斷原本字串之後取代的字串,而所取代的字串長度也包含在原本截短的長度 內。預設狀況下,函式在截斷時會參照字的邊界而截斷的,如果你希望在某個長度後直接截斷而 不考慮是否會截斷字的話,請使用第三個參數且將其設定為 true。

Example 5-20. truncate

<?php
    
$smarty
= new Smarty;
$smarty->assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.');
$smarty->display('index.tpl');

?>

where index.tpl is:

其中 index.tpl 的內容為:

{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}

This will output:

輸出結果為:

Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after...
Two Sisters Reunite after
Two Sisters Reunite after---
Two Sisters Reunite after Eigh
Two Sisters Reunite after E...