3

I am currently able to get currency symbol in symfony2 controller

$formatter = new \NumberFormatter($this->getRequest()->getLocale(),\NumberFormatter::CURRENCY);
$symbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);

and then pass it to twig.

However, because I need to get this currency symbol in many twig templates, inserting that piece of code in the corresponding controllers is not a pleasant thing to do. So, is there any better/easier way to do this directly in twig?

Thanks.

4

1 回答 1

5

这是我创建自定义树枝功能的方法

namespace Acme\DemoBundle\Twig;

class AcmeExtension extends \Twig_Extension
{
    public function getFunctions() {
        return array(
            'currencySymbol' => new \Twig_Function_Method($this, 'currencySymbolFunction'),
        );
    }

    public function currencySymbolFunction($locale) {
        $locale = $locale == null ? \Locale::getDefault() : $locale;
        $formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
        $symbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);

        return $symbol;
    }

    public function getName() {
        return 'acme_extension';
    }
}

服务:

acme.twig.acme_extension:
    class: Acme\DemoBundle\Twig\AcmeExtension
    tags:
        - { name: twig.extension }

因为我需要获取 symfony2 parameters.ini 中当前定义的语言环境并将其传递给 twig 函数,所以我定义了一个全局 twig 值:

twig:
    globals:
        locale: %locale%

最后在树枝模板中:

{{ currencySymbol(locale) }}
于 2013-03-15T12:40:21.267 回答