3

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.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
newdeveloper
  • 534
  • 3
  • 17
  • "This fails to truncate." - What **exactly** happens in that case? Does it shows an error? Or prints something? – Tsyvarev Apr 20 '22 at 08:05
  • No it doesn't fail or anything. prints the full string `foo bar baz qux` and truncate is ignored. – newdeveloper Apr 20 '22 at 10:43
  • So, the difference is not about a string variable and a string literal, it is about the **content** of the string, am I correctly understand your last edit? Please, update the question title and beginning of the post to reflect **actual** state of affairs. In the current form the question is quite misleading. – Tsyvarev Apr 20 '22 at 11:07

2 Answers2

3

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] }}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
1

I had to add an optional leeway value. Not sure what the leeway value is doing. But it's truncating correctly.

pagetitle='whateverwhatever'
{{ pagetitle | truncate(9,True,'',0) }}
newdeveloper
  • 534
  • 3
  • 17