grav icon indicating copy to clipboard operation
grav copied to clipboard

|truncate filter doesn't truncate at the nearest sentence end

Open u07 opened this issue 10 months ago • 3 comments

The docs don't match reality. Truncate cuts at the nearest word, not the end of a sentence.

Example: summary: 'one not so long sentence. two sentences'|truncate(5, true)|raw

Renders as: one not…

Image

u07 avatar Feb 14 '25 10:02 u07

Everything works as instructed. What do you want to return?

If one n…, then use 'one not so long sentence. two sentences'|truncate(5)|raw (without parameter true).

petira avatar Feb 17 '25 07:02 petira

In my world a sentence will end at the nearest sentence-ending punctuation (like ., !, or ?)

u07 avatar Feb 17 '25 09:02 u07

Although the example used in the documentation is in fact correct (by chance), the explanation is not...

The following code used as an example in the docs returns the truncated texts as expected:

{{ 'one sentence. two sentences.'|truncate(5)|raw }}         => one s…
{{ 'one sentence. two sentences.'|truncate(5, true)|raw }}   => one sentence.…

However, the explanation is not correct. The truncate(5, true) function does not search for the end of the sentence, but instead for a breaking character, which is a space by default.

See the code for truncate.

You can provide your own breaking character, like a period, but you cannot provide multiple punctuations, or a regex.

public static function truncate($string, $limit = 150, $up_to_break = false, $break = ' ', $pad = '…')

You might consider creating a PR on the docs. Or you could create a PR to improve the truncate function itself. Or even both...

Btw. when using the content of variable page.summary, you are truncating a string containing HTML, like <p>one sentence...</p>. This will of course impact the truncation. You should in that cases consider using one of the other truncation functions.

pamtbaau avatar Feb 18 '25 12:02 pamtbaau