Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting money in twig templates

Are there any filters or something like that in twig template engine to format money or numbers?

like image 882
umpirsky Avatar asked May 07 '11 11:05

umpirsky


3 Answers

The number_format filter has been included in the Twig core since the end of December 2011. The relevant commit is here.

Usage: number_format(decimals, decimalSeparator, thousandSeparator)

{{ total|number_format(2) }}
{{ total|number_format(0, '.') }}
{{ total|number_format(2, '.', ',') }}

Read more about it in the docs

like image 188
Jrgns Avatar answered Nov 18 '22 22:11

Jrgns


The Twig Extensions library contains a number of useful extensions for Twig. With the release of version 1.2.0, a localizedcurrency filter has been added to the Intl extension. As the name suggests, this filter will format a number based on the current locale. It uses PHP's NumberFormatter class to do so.

Usage

This filter is very easy to use. The only required argument for the filter is the 3-letter ISO 4217 currency code. For instance, to display an amount of 27.99 in Euros, use the following line of code:

{{ price|localizedcurrency('EUR') }}

This will display different results depending on the locale:

  • €27.99 if the locale is set to en
  • 27,99 € if the locale is set to fr
  • € 27,99 if the locale is set to nl

Installation / setting the locale

Installation instructions for the Intl extension can be found in this seperate answer.

like image 22
Nic Wortel Avatar answered Nov 18 '22 23:11

Nic Wortel


If you are using an older version of twig and you don't want to install any extensions you can use the format filter like this:

{{ "%.2f"|format(total) }}

Not very nice, but it works.

Basically format works like PHP's sprintf function

like image 11
Jens Avatar answered Nov 18 '22 22:11

Jens