Search code examples
phpsymfonytwigsetlocale

Symfony 2 setlocale (LC_ALL, 'de_DE')


I would like to display a date in TWIG in German.

{{ event.beginnAt |date('l d.m.Y')}}

But the output is "Friday 28.06.2013".

Where should I use the setlocale function that displays the date in German?


Solution

  • You need to enable twig intl extension (it requires enabled intl functions in php) a then you just use:

    {{ event.beginAt | localizeddate('full', 'none', locale) }}
    

    Edited:
    If you want to just localized name of day, you can create your own Twig extension:

    src/Acme/Bundle/DemoBundle/Twig/DateExtension.php

    namespace Acme\Bundle\DemoBundle\Twig;
    
    class DateExtension extends \Twig_Extension
    {
    
        public function getFilters()
        {
            return array(
                new \Twig_SimpleFilter('intl_day', array($this, 'intlDay')),
            );
        }
    
        public function intlDay($date, $locale = "de_DE")
        {
    
            $fmt = new \IntlDateFormatter( $locale, \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'Europe/Berlin', \IntlDateFormatter::GREGORIAN, 'EEEE');
            return $fmt->format($date);
        }
    
        public function getName()
        {
            return 'date_extension';
        }
    }
    

    Then register it in services.yml

    src/Acme/Bundle/DemoBundle/Resources/config/services.yml

    parameters:
        acme_demo.date_extension.class: Acme\Bundle\DemoBundle\Twig\DateExtension
    
    services:
        acme_demo.twig.date_extension:
            class: %acme_demo.date_extension.class%
            tags:
                - { name: twig.extension }
    

    In your Twig template you can use just:

    {{ event.beginAt|intl_day }} {{ event.beginAt|date('d.m.Y') }}