4

How can I display the currency symbol in twig? I saved the numeric value of the symbol like:

for EURO : €
for DOLLAR: $

When I render these values, & is converted to & and the currency symbol does not show. Any idea will be greatly appreciated. Thank you.

Floricel
  • 791
  • 2
  • 9
  • 20

3 Answers3

7

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';
    }
}
Ahmed Siouani
  • 13,701
  • 12
  • 61
  • 72
2

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

Floricel
  • 791
  • 2
  • 9
  • 20
  • Yes, by using raw filter your variable is not escaped. Btw, I added a much cleaner solution that allows you render any currency symbol. – Ahmed Siouani Apr 23 '13 at 14:55
1

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

Schyzophrenic
  • 131
  • 1
  • 9