Grav: Truncate to closest sentence-end

Created on 13 Mar 2018  路  9Comments  路  Source: getgrav/grav

Not sure if this is a bug or just a mistake in documentation, but according to the docs this should truncate a string to the nearest sentence-end after 5 characters: truncate(5, true).

However, when I use that it simply truncates to the nearest word-end after 5 characters (like safe_truncate).

Is this a bug or what?

question

All 9 comments

Actual example I'm testing with:

'Hey this is a sentence. And this is another sentence.'|truncate(12, true)

I would expect the output to be Hey this is a sentence.
But what I'm getting is Hey this is a

If you set that second value to try, the first value is the number of words, try:

{{ 'Hey this is a sentence. And this is another sentence.'|truncate(4, true) }}

Thanks for the tip, sadly that didn't work for me. The output I get with that exact code is Hey this
Which makes sense if 4 is the number of characters, not words. Was it counting words for you?

Unrelated side note: I noticed the Grav backend now says "made by Trilby", and the Trilby site has been updated to focus on Grav. This makes he happy because I love Grav and I'm glad it's growing enough for Trilby to focus on supporting it.

I was just looking at the Truncator code, but now I'm seeing that |truncate uses the older Utils::truncate() method, but Utils::safeTruncate() is using the new Truncator class with a word-safe option, try this:

{{ 'Hey this is a sentence. And this is another sentence.'|safe_truncate(12) }}

And yes, Trilby Media is comprised of the same folks from RocketTheme, but as Trilby is focused on professional services for Grav specifically, it makes more sense for Grav to come under it's auspices.

The output I get for that is Hey this is a
I did a little more testing and is seems truncate(n, true) and safe_truncate(n) are equivalent, both cut to the nearest word.

Truncating to the nearest sentence would be handy, but it's not a big deal. This will work fine for what I'm doing. Thanks for the help!

You could try adding the $break option into the mix, it will never be accurate but if you assume all your sentences end with a . (period), you could set that.

Discalimer, I haven't actually tested this :)

truncate(12, true, '. ') <- I have a space after . but you could play with that so it's just .

Cool, thanks. I'll give this a shot.

@w00fz that seems to work perfectly. I did it without the space after the period: truncate(10, true, '.')

Thanks for the suggestion!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

flaviocopes picture flaviocopes  路  5Comments

josefstr picture josefstr  路  4Comments

adrianschembri picture adrianschembri  路  3Comments

bmrankin picture bmrankin  路  3Comments

vico93 picture vico93  路  5Comments