Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 truncate string variable not working

My Python application is using Jinja for the front end. I am trying to truncate the variable that is a string, however it is not working.

I can truncate a string but not a variable.

This fails to truncate:

{{ pagetitle | truncate(9,True,'') }}

This truncates to foo bar b:

{{ "foo bar baz qux"|truncate(9,True,'') }}

I think I have figured this out.
It appears to only trim phrases? {{ "foo bar baz qux"|truncate(9,True,'') }} will truncate, however {{ "foobarbazqux"|truncate(9,True,'') }} will not truncate.

like image 425
newdeveloper Avatar asked Sep 15 '25 08:09

newdeveloper


1 Answers

There is a fourth parameter to truncate, and this is the one allowing you to achieve what you are looking for.

Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.

So, given:

{{ 'foobarbazqux' | truncate(9, True, '', 0) }}

This yields:

foobarbaz

So, in your case:

{{ pagetitle | truncate(9, True, '', 0) }}

This said, since you are using truncate without an ellipsis and want to cut in word (the second parameter is True), you could also consider going for a simpler slice:

{{ 'foobarbazqux'[0:9] }}

So, in your case:

{{ pagetitle[0:9] }}
like image 136
β.εηοιτ.βε Avatar answered Sep 18 '25 10:09

β.εηοιτ.βε