Using truncate() in templates

Hi, I try to use truncate in template but the result is very inconsistent … does work, does not, very weird. . I use grav

Someone may help me … By the way there is nothing regarding truncate() filter in the docs :


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:

{{ content|striptags|truncate(200) }}

Thanks. Ok for the documentation part but what about the problem I mentioned ?

Did you not read the stiptags comment I made? You really didn’t provide any specifics about your problem.

Yes, I noted about the striptags but I still have this weird result with inconsistent length

My code :

{{ portfolio.desc|striptags|truncate(50) }}

and the result :

137 chars for 1st block, 200 for second, 120 for third …

I will test this further!

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) }}

Will print: one sentence.

Thanks. Waiting for the next release. For myself and others, I just bookmark the concerned commit :