Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: How can I set twig |date("d F, Y") filter to output months in Swedish?

I'm having problems with the |date("d F, Y") filter in my twig templates.

I want the months to be outputted in Swedish. I have tried setting "locale: sv" in my parameters.yml files but I get no effect.

It was working before I upgraded to from Symfony 2.1 to 2.3 so I think that might have something to do with it.

Any thoughts on how to fix this?

like image 344
tirithen Avatar asked Jun 28 '13 11:06

tirithen


3 Answers

The Twig Intl Extension

You can use the Twig Intl Extension found in fabpot's official Twig extension repository.

It provides a localized date filter which can be used like this:

{{ date | localizeddate('full', 'none', app.request.locale ) }}

use app.request.locale as third parameter for current locale or just 'sv'.

Integration into your project

add the official extensions to your composer.json using:

composer require twig/extensions:1.0.*@dev
composer update twig/extensions

config.yml

#enable intl extensions
services:
    twig.extension.intl:
        class: Twig_Extensions_Extension_Intl
        tags:
            - { name: twig.extension }

quick tip:

another handy extension is the Text extension providing truncate,...etc filters

services:
    twig.extension.text:
        class: Twig_Extensions_Extension_Text
        tags:
            - { name: twig.extension }
like image 165
Nicolai Fröhlich Avatar answered Oct 10 '22 20:10

Nicolai Fröhlich


I will make an addition to solution posted by @nifr.

In order to use your date format install the Twig Intl Extension and than you can use:

{{ date|localizeddate('none', 'none', app.request.locale, null, 'dd MMMM, yyyy') }}

The last argument in my example is a date format - here is a documentation: http://userguide.icu-project.org/formatparse/datetime

Here is the Twig Intl Extension documentation: https://twig-extensions.readthedocs.io/en/latest/intl.html

like image 39
Seb Avatar answered Oct 10 '22 20:10

Seb


|date filter use DateTime::format function which doesnt support locales. See this question and write your own twig extension.

like image 2
Alexey B. Avatar answered Oct 10 '22 20:10

Alexey B.