首页 > 解决方案 > 通过核心扩展更改 number_format 过滤器的默认值

问题描述

我想更改number_formaton twig 的默认设置。在他们的文档中,他们展示了如何做到这一点

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

我的问题是使用 Symfony 时我可以在哪里插入此代码?

标签: twigsymfony5

解决方案


您可以在 twig.yaml 配置中更改此设置。

# app/config/packages/twig.yaml

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

或者如果您可以使用事件订阅者手动将其更改为内核请求事件。

<?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, '.', ',');
    }
}

推荐阅读