How can I set the default date format for Twig templates in Symfony2?

For a more detailed solution.

in your bundle create a Services folder that can contain the event listener

namespace MyApp\AppBundle\Services;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class TwigDateRequestListener
{
    protected $twig;

    function __construct(\Twig_Environment $twig) {
        $this->twig = $twig;
    }

    public function onKernelRequest(GetResponseEvent $event) {
        $this->twig->getExtension('core')->setDateFormat('Y-m-d', '%d days');
    }
}

Then we will want symfony to find this listener. In the Resources/config/services.yml file put

services:
    twigdate.listener.request:
        class: MyApp\AppBundle\Services\TwigDateRequestListener
        arguments: [@twig]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

by specifying @twig as an argument it will be injected into the TwigDateRequestListener

Make shure that your importing the services.yml at the top of app/config.yml

imports:
    - { resource: @MyAppAppBundle/Resources/config/services.yml }

Now you should be able to skip the format in the date filter as such

{{ myentity.dateAdded|date }}

and it should get the formatting from the service.


As of Symfony 2.7, you can configure the default date format globally in config.yml:

# app/config/config.yml
twig:
    date:
        format: d.m.Y, H:i:s
        interval_format: '%%d days'
        timezone: Europe/Paris

The same is also possible for the number_format filter. Details can be found here: http://symfony.com/blog/new-in-symfony-2-7-default-date-and-number-format-configuration


In controller you can do

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

Tags:

Twig

Symfony