Set Default Number Format for Twig Template in Symfony 6

Set Default Number Format for Twig Template in Symfony 6

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

This tutorial shows how to set number format for Twig template in Symfony 6 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 Twig templates:

config/packages/twig.yaml

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

In order 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\Annotation\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.