Jinja: truncate filter can no longer truncate on the right side

Created on 27 Aug 2019  ·  9Comments  ·  Source: pallets/jinja

Before commit #610 it was possible to do right side truncation, e.g. if one wanted to split a month name into abbreviated (3 char long) and non-abbreviated form it would be possible to achieve with:

"November"|truncate(3, True, '')
"November"|reverse|truncate(-3, True, '')|reverse

The above would produce "Nov" and "ember" due to the way how string functions work:

>>> s='123456789'
>>> s[:3]
'123'
>>> s[:-3]
'123456'
>>>

I think that commit removed a very useful functionality that is no longer achievable with the current version of Jinja (due to an explicit assert() that requires a positive truncation length to be provided. I would suggest to remove that assert to give the opportunity to truncate a string on any end using the truncate filter.

Most helpful comment

Try adding parentheses: {{ (article.date|strftime('%B'))[:3] }}

All 9 comments

Your usecase is not what truncate is meant for it's for truncating long strings (usually with "..." at the end). You can simply use {{ 'November'[:3] }} to get the first three chars in Jinja...

@ThiefMaster, I actually want to get "ember" from "November", "ober" from "October", etc. Not the first three characters. However, thanks for the tip. I appreciate it. In any case, I just submitted a PR that adjust the logic to preserve all the introduced changes but also makes it possible to truncate for either side of the string :)

[3:] then?

@ThiefMaster, it seems your hint works with literal strings only. I am using Pelican (a static website generator) and my Jinja2 code is something like the following:

{{ article.date|strftime('%B')|truncate(3, True, '') }}

It seems that it is not possible to use the proposed [:3] in this case, this is why I was relying on truncate.

Try adding parentheses: {{ (article.date|strftime('%B'))[:3] }}

@ThiefMaster, you are a legend! It works this way. Thanks. However, I still believe that my PR #1053 improves the function by introducing abs() around the length parameter. However, now that you provided a workaround my life is happy again :)

Also, regarding the purpose of the truncate function, it seems the common assumption is that there are only LTR languages, but this is not true. There are RTL languages as Farsi, etc, where truncation should be done on the other end :)

I'm not an expert on RTL, but I'm fairly sure that's a UI thing only, the string is still LTR internally.

Closing as I don't think truncating on the left was ever intended. If you need specific string manipulations, write a specific filter, especially for the given example.

Was this page helpful?
0 / 5 - 0 ratings