Set Default Date Format and Time Zone for Twig Template in Symfony 7

Set Default Date Format and Time Zone for Twig Template in Symfony 7

Symfony framework applies the default date format and time zone when the date filter is used in the Twig template. The default date format and time zone can be overridden by providing arguments for the date filter. It is not good solution when custom date format and time zone should be applied for all the Twig templates.

This tutorial shows how to set default date format and time zone for Twig template in Symfony 7 application.

The format and timezone options can be used under the twig.date key to define the default date formatting and time zone for all the Twig templates:

config/packages/twig.yaml

twig:
    date:
        format: 'M d, Y g:i A'
        timezone: 'America/New_York'

To test, create the controller and template which uses date filter:

templates/test/index.html.twig

{{ 'now'|date }}

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        return $this->render('test/index.html.twig');
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.