I'm trying to display prices in a specific format with twig/symfony. I would like to consider the null case (there is no price) but I get this Symfony error:
The "defined" test only works with simple variables.
Here is my code in twig :
<td>{{ _self.formatRemuneration(remunerationValues.variable_monthly_remuneration|number_format(2, ',', ' ') ?? null) }}</td>
Without this ?? null
part it only works if a price exists in the database. I don't take the null case into account.
I also tried to move the filter (|number_format(2, ',', ' ')
) inside the macro but I get errors or 0.00 values instead of nothing.
{% macro formatRemuneration(remuneration) %}
{{ remuneration is not null ? 'profile.remuneration.formated'|trans({'remuneration': remuneration}, 'company_position') : '' }}
{% endmacro %}
Can you help me write this condition?
CodePudding user response:
To start, I'm not sure why you are doing something called formatRemuneration
and trying to apply the the filter number_format
both at the same time.
If I were you I would move the filter inside your macro, in which you then could test for a null
value when the price isn't set and return whatever you want, e.g. Not applicable
To fix the error you would only need to evaluate the variable, not the whole line, see below. This is because the filter number_format
return an object of the instance Twig\Markup
<td>{{ _self.formatRemuneration(remunerationValues.variable_monthly_remuneration ?? null) }}</td>
If you can't move the filter number_format
for whatever reason, you would need to change the snippet to the following:
<td>{{ _self.formatRemuneration((remunerationValues.variable_monthly_remuneration ?? null)|number_format(2, ',', ' ')) }}</td>
Keep in mind null
will get converted to 0.00