Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig: show the name of the months based on the current locale

Tags:

twig

symfony

I'm just trying to show the name of the months based on the current locale.

{{ event.date|date('F') }}

but the months are always shown in english...

I have tried this code below I found here, but the result is the same...

class Helper_Twig extends Twig_Extension
{
    public function getFilters()
    {
        return array(
            'datetime' => new Twig_Filter_Method($this, 'datetime')
        );
    }

    public function datetime($d, $format = "%B %e")
    {
        if ($d instanceof \DateTime) {
            $d = $d->getTimestamp();
        }

        return strftime($format, $d);
    }

    public function getName()
    {
        return 'Helper';
    }
}

NOTE: In the controller I'm checking the current locale using $request->getLocale and it corresponds to the locale parameter I'm switching in parameters.yml.

What is the problem?

like image 427
ziiweb Avatar asked Jul 30 '12 19:07

ziiweb


2 Answers

Since you defined datetime TwigFilter, you don't have to call {{ event.date|date('F') }}

Instead, you should call this {{ event.date|datetime('%B') }}

like image 122
Vitalii Zurian Avatar answered Oct 09 '22 10:10

Vitalii Zurian


If you have installed the IntlExtension you can use format_datetime with custom pattern.

{{ event.date|format_datetime(pattern="MMMM") }}

docs:

  • https://twig.symfony.com/doc/3.x/filters/format_datetime.html
  • https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax
like image 35
Julien Avatar answered Oct 09 '22 11:10

Julien