How to display a twig date in french
You can work with hash (key-value array) and match it with the date object you are manipulating.
For example, to get the day of the week of today in words:
{% set trans_day_hash = {
"Monday": "Lundi",
"Tuesday": "Mardi",
"Wednesday": "Mercredi",
"Thursday": "Jeudi",
"Friday": "Vendredi",
"Saturday": "Samedi",
"Sunday": "Dimanche"
}
%}
{{ trans_day_hash["now"|date('l')] }}
Another good practice is:
{{ match.date|date("l")|trans }}
This way you can translate using your prefered translation file.
The date
filter in Twig is not well suited for localized date formatting, as it is based on PHP's DateTime::format
. One option would be to use the localizeddate
filter instead, provided by the Intl Extension.
This extension is not delivered on a default Symfony installation. You will find it in the official Twig extensions repository :
composer require twig/extensions
Then, just declare this extension as a service in services.yml
for instance :
services:
twig.extension.intl:
class: Twig_Extensions_Extension_Intl
tags:
- { name: twig.extension }
I am using format_datetime
twig filter with locale
and pattern
arguments as follow:
{{ service.date|format_datetime(locale='fr',pattern="EEEE dd MMMM YYYY") }}
which outputs for example:
vendredi 27 novembre 2020
lundi 02 novembre 2020
vendredi 30 octobre 2020
see this resource for date pattern.