Skip to main content

Localising dates in twig templates

An article from ComputerMinds - Building with Drupal in the UK since 2005
14th Aug 2018

James Williams

Senior Developer
Hey, you seem to look at this article a lot! Why not Bookmark this article so you can find it easily in the future?

A client noticed the dates on their news articles were not being translated into the correct language. The name of the month would always appear in English, even though all the month names had themselves been translated and showed correctly elsewhere. The problem turned out to be down to the twig filter being used in the template to format the date. This is what we did have:

{% set newsDate = node.getCreatedTime|date('j F Y') %}
{% trans %} {{ newsDate }}{% endtrans %}

So this would produce something like '1 March 2018' instead of '1 März 2018' when in German. This was because twig's core date() filter simply isn't aware of Drupal's idea of language.

I switched out the date() filter and used Drupal core's own format_date() filter instead, which uses Drupal's own date.formatter service, which is aware of language. It ensures the month name is passed through t() to translate it, separately to the rest of the numbers in the date. So it now looks like this:

{% set newsDate = node.getCreatedTime|format_date('custom', 'j F Y') %}
{% trans %} {{ newsDate }}{% endtrans %}

Having done that, I realise the original code was the equivalent of doing this:

t('1 March 2018');

(I'm less of a front-end coder, so putting it in PHP makes it more obvious to me than twig code!)

So the date actually was translatable, but only as the whole string -- so unless the translators had gone through translating every single individual date, the German month name was never going to show!

What I needed was the twig equivalent of using placeholders like this PHP example:

t('My name is @name, hello!', ['@name' => $name]);

When you use variables between twig's trans and endtrans tags, they really are treated by Drupal as if they were placeholders, so this is the twig version:

{% trans %} My name is {{ name }}, hello! {% endtrans %}

This helped me understand twig that little bit more, and appreciate how to use it better! Regardless of formatting dates, I now know better how to set up translatable text within templates, hopefully you do too :-)

Hi, thanks for reading

ComputerMinds are the UK’s Drupal specialists with offices in Bristol and Coventry. We offer a range of Drupal services including Consultancy, Development, Training and Support. Whatever your Drupal problem, we can help.