Changing the default of number_format filter through the core extension

Viewed 88

I want to change the default settings of number_format on twig. In their docs they show how to do this

$twig = new \Twig\Environment($loader);
$twig->getExtension(\Twig\Extension\CoreExtension::class)->setNumberFormat(3, '.', ',');

My question is where I could insert this code when using Symfony?

1 Answers

you can change this setting in twig.yaml configuration.

# app/config/packages/twig.yaml

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

or if you can manually change it using event subscriber to kernel request event.

<?php

namespace App\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
use Twig\Extension\CoreExtension;

class TwigSettingListener implements EventSubscriberInterface
{
    private $twig;
    public function __construct(Environment $twig)
    {
        $this->twig = $twig;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => 'onKernelRequest',
        ];
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $this->twig->getExtension(CoreExtension::class)
            ->setNumberFormat(3, '.', ',');
    }
}
Related