New in Symfony 2.7: Default Date and Number Format Configuration

Contributed by
Christian Flothmann
in #13554.

When you use the date filter to display dates in Twig templates, Symfony applies the default date formatting defined in the Twig Core extension. The same goes for numeric values formatted with the number_format filter.

These default formats can be overridden using the arguments of each filter:

1
{{ post.published_at|date("F jS \\a\\t g:ia") }}

However, if you use the same custom date or number formatting for all the values rendered in the application templates, this technique is very cumbersome. In Symfony 2.6 you can set the default formatting inside a controller as follows:

1
$this->get('twig')->getExtension('core')->setDateFormat('d/m/Y', '%d days');

Setting up the default formatting for the entire application is even more complex, because you usually need to set up a dedicated listener. Symfony 2.7 adds two new Twig configuration options to define the default formatting of both numbers and dates without the need to write custom code.

Use the date configuration option under the twig key to override any of the default date formatting options:

1
2
3
4
5
# app/config/config.yml
twig:
    date:
        format: d.m.Y, H:i:s
        interval_format: '%%d days'

You can also define the timezone option to use it when formatting dates:

1
2
3
4
5
# app/config/config.yml
twig:
    date:
        # ...
        timezone: Europe/Paris

Similarly, the default formatting of numeric values can now be defined using the new number_format option under the twig key:

1
2
3
4
5
6
# app/config/config.yml
twig:
    number_format:
        decimals: 2
        decimal_point: ','
        thousands_separator: '.'

Comments

Very nice! Thank you ... Can we still specify e.g. thousands_separator value as a reference to parameters?
Thank you for this. Implementing that listener over and over was getting old :)
Would be interesting to have a similar configuration option for forms so that the default view_timezone could be set
How does this work with i18n? More here: https://github.com/symfony/symfony/pull/13554#issuecomment-90076488

Scott
Excellent! Thanx

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.