johnkork
johnkork

Reputation: 664

Twig's attribute function : formatting numbers

In a Symfony2 application, I use Twig's attribute function to display properties of a product on a generic manner : I have an array of names of properties, and cycling through it I display properties :

{% for property in arrayProperties %}
    {{ attribute(entity, property)|trans }}
{% endfor %}

These properties can be litteral OR numeric, eg:

The problem is that float properties are displaying this way :

size_of_Y : 0.42

size_of_Z : 0.84848

While I would like to display with a comma separator, this way :

size_of_Y : 0,42

size_of_Z : 0,84848

It seems I can't use the number_format function right after the attribute function since it will transform my litteral values in 0's, and even if I can find a way to test if the value displayed is a numeric or litteral value (a is_numericish function), I won't be able to determine the scale of the property (how many numbers after the comma I should display, which is the first argument of number_format).

Is there a generic way to change how Twig is displaying these properties ?

In my Twig's configuration (config.yml), I already have :

number_format:
    decimals: 0
    decimal_point: ','
    thousands_separator: ' '

Which seems to work for the rest of the application, where I don't use the attribute function to display properties.

Thanks !

Upvotes: 2

Views: 589

Answers (2)

Carlos Granados
Carlos Granados

Reputation: 11351

You need to write your own Twig extension to handle this:

Twig Extensions

Upvotes: 1

COil
COil

Reputation: 7606

So define additional types in your arrayProperties, add a type and a scale so you can do tests in the loop and so you don't call trans for numeric values.

{% for property_name, property_infos in properties %}
    {% if property_infos.type == 'numeric' %}
        {{ attribute(obj, property_name)|number_format(property_infos.scale, ',', ',') }}<br/>
    {% else %}
        {{ attribute(obj, property_name)|trans }}<br/>
    {% endif %}
{% endfor %}

Upvotes: 1

Related Questions