Set Default Number Format for Twig Template in Symfony 7

Set Default Number Format for Twig Template in Symfony 7

Symfony framework applies the default number format when the number_format filter is used in the Twig template. The arguments can be provided for the number_format filter to override the default number format. This technique can be inconvenient when custom number format should be applied for all the Twig templates.

This tutorial shows how to set number format for Twig template in Symfony 7 application.

The decimals, decimal_point and thousands_separator options can be used under the twig.number_format key to define the default number formatting for all the Twig templates:

config/packages/twig.yaml

twig:
    number_format:
        decimals: 2
        decimal_point: ','
        thousands_separator: '.'

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

templates/test/index.html.twig

{{ 1000.356|number_format }} {# 1.000,36 #}

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.