Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localize dates in twigs using Symfony 2

To format a date in twig you usually use something like:

{{ meeting.date|date("m/d/Y") }}

Now, I have to localize this date (US m/d/y, NL d/m/y). What would be the best practice to do this in the twig? I do use Symfony 2, a workaround would be to do the translation in the controller but i would like to do this in the twig.

like image 993
Roel Veldhuizen Avatar asked Feb 28 '12 10:02

Roel Veldhuizen


2 Answers

What about the Intl Twig extension?

Usage in a twig template:

{{ my_date | localizeddate('full', 'none', locale) }}
like image 129
Brian Clozel Avatar answered Oct 15 '22 23:10

Brian Clozel


I didn't want to install a whole extensions just for this stuff and need to do a few things automatically: It's also possible to write a helperclass (or expand an existing helper) in Bundle/Twig/Extensions for example like this:

public function foo(\Datetime $datetime, $lang = 'de_DE', $pattern = 'd. MMMM Y')
{
    $formatter = new \IntlDateFormatter($lang, \IntlDateFormatter::LONG, \IntlDateFormatter::LONG);
    $formatter->setPattern($pattern);
    return $formatter->format($datetime);
}

twig-Template:

{{ yourDateTimeObject|foo('en_US', 'd. MMMM Y') }}

The result is "12. February 2014" (or "12. Februar 2014" in de_DE and so on)

like image 30
Franziska Avatar answered Oct 16 '22 00:10

Franziska