Displaying currency symbol in twig

不想你离开。 提交于 2019-12-05 19:06:57

To do it well, you've to add a function or a filter which is called as a helper to render currency symbols within your twig templates.

To use the following function,

{{ currency('en_US') }}

You've to add a twig extension as follow,

xxx.twig.your_extension:
    class: XXX\YourBundle\Twig\YourExtension
    tags:
        - { name: twig.extension }

You've then to add a currency function,

namespace XXX\YourBundle\Twig;

class YourExtension extends \Twig_Extension
{
    public function getFunctions() {
        return array(
            'currency' => new \Twig_Function_Method($this, 'currencyFunction'),
        );
    }

    public function currencyFunction($locale) {
        $formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
        $symbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);

        return $symbol;
    }

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

I figured it out. When rendering, I need to use the raw filter of twig.

It is an old thread, but for the new people coming here, Twig has now an extension for the currency symbols (with new filters |currency_symbol ) as you can see in the documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!