Sep 14, 2020 in

I had to output my dates in dutch format, but struggled a bit to do it automatically. I discovered a nice twig built-in feature.

In Twig, you can use built-in translation contexts.

The default formatting was:

 {% set date = node.created.value|date("j") ~ ' ' ~ node.created.value|date("F") ~ ' ' ~ node.created.value|date("Y") %}
// now {{ date }} outputs: 8 August 2020

When I use translation contexts, it worked as expected:

{% set date = node.created.value|date("j") ~ ' ' ~ node.created.value|date("F")|t({}, {'context' : 'Long month name'}) ~ ' ' ~ node.created.value|date("Y") %}
// now {{ date }} outputs: 8 augustus 2020

Further, I discovered  you can translate a string in a Twig file with a specified context in two ways :

{{ "Text to translate"|t({}, {'context' : 'Context name'}) }}

and

{% trans with {'context': 'Context name'} %}
    Text to translate
{% endtrans %}