Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
u07 opened this issue Feb 14, 2025 · 3 comments
Open

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

u07 opened this issue Feb 14, 2025 · 3 comments

Comments

@u07
Copy link

u07 commented Feb 14, 2025

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 u07 changed the title |truncate filter does not truncate to closest sentence-end |truncate filter doesn't truncate at the nearest sentence end Feb 14, 2025
@petira
Copy link

petira commented Feb 17, 2025

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

@u07
Copy link
Author

u07 commented Feb 17, 2025

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

@pamtbaau
Copy link
Contributor

pamtbaau commented Feb 18, 2025

Although the example used in the documentation is in fact right, 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 point, 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants