Looks like we neglected to add that to the docs. Will get to it soon. If you look at the code in the TwigExtension.php class you will see:
/**
* Truncate content by a limit.
*
* @param string $string
* @param int $limit Max number of characters.
* @param string $break Break point.
* @param string $pad Appended padding to the end of the string.
* @return string
*/
public function truncateFilter($string, $limit = 150, $break = ".", $pad = "…")
{
// return with no change if string is shorter than $limit
if (strlen($string) <= $limit) {
return $string;
}
// is $break present between $limit and the end of the string?
if (false !== ($breakpoint = strpos($string, $break, $limit))) {
if ($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}
Basically it limits a string to a configurable number of characters and appends a pad (...) to the end. Note however this doesn’t strip tags, so that might be causing your inconsistencies. You can pass your content through striptags filter first to sort this out though:
Ok I looked and I found the code was actually smarter than I remember. The logic was such that it would go to the end of the sentence given any character count. This way, your truncated text is not cut off, it will go to the nearest end of the sentence.
However, I can appreciate this is probably not what is wanted all the time so in the next release of Grav, this logic will be turned off by default, but you can still use it if you pass a second param of true, so:
{{ 'one sentence. two sentences'|truncate(5) }}
Will print: one s...
{{ 'one sentence. two sentences'|truncate(5, true) }}