how to get currency symbol in twig, symfony2?

symfony, symfony-2.1, twig

Solution

Here is how I create the custom twig function

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';
    }
}

The service:

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

Because I need to get and pass the current defined locale in symfony2 parameters.ini into the twig function, I define a global twig value:

twig:
    globals:
        locale: %locale%

And finally in twig template:

{{ currencySymbol(locale) }}

Problem

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.

Original source