New in Symfony 2.7: Default Date and Number Format Configuration

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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: '.'
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Scott