Templating: Jinja2 translate() function

Just discovered the translate() function in Jinja2 that is very little documented, and could be quite useful in string-tidying and replacing operations. I stumbled across it whilst on this topic, looking for a short solution for mapping German month abbreviations to English ones (although note that the name “translate” is not about translating languages, but sets of characters).

Here’s two templates to do that job, first with a sequence of replaces, then with translate(). The dictionary full of numbers below is populated with the character codes to do the same changes as the replaces: ä→a, i→y, k→c and z→c, which are what’s needed to change the German abbreviations to English ones.

# using replace:
{{ 'JanFebMärAprMaiJunJulAugSepOktNovDez'|replace('ä','a')|replace('i','y')|replace('k','c')|replace('z','c')

# using translate():
{{ 'JanFebMärAprMaiJunJulAugSepOktNovDez'.translate({228:97,105:121,107:99,122:99}) }}

# both templates return 'JanFebMarAprMayJunJulAugSepOctNovDec'

This works the same as the Python translate() function (docs), although there doesn’t appear to be a maketrans() in Jinja, so you have to provide a dictionary.

To make it a bit more readable, you can use the ord filter (documented at the bottom of this section) that returns a character code — so this is equivalent to the above template, written for readability:

{{ 'JanFebMärAprMaiJunJulAugSepOktNovDez'.translate({ 'ä'|ord: 'a'|ord,
                                                      'i'|ord: 'y'|ord,
                                                      'k'|ord: 'c'|ord,
                                                      'z'|ord: 'c'|ord}) }}

This could be useful if you need to perform a set of replacements in more than one place within a template: you could define the dictionary in advance then refer to it, which would not be possible with the replace method:

{% set ger2eng = {228:97,105:121,107:99,122:99} %}
{% set test_date = '30 Okt 2023' %}
{{ 'JanFebMärAprMaiJunJulAugSepOktNovDez'.translate(ger2eng) }}
{{ test_date.translate(ger2eng) }}

Probably only useful in rare occasions, but I’m glad I found it.

1 Like

it’s a string method

Here’s a list of all string methods.

1 Like