Twig: default filter does not work on (bool) false in array
The following behavior seems odd to me. A value of an array should be checked for existence when using the default filter (the second dump).
{% set var = { 'foo': 0, 'bar': false } %}
{# expected 0, got 0 #}
{{ dump(var.foo|default(true)) }}
{# expected false, got true #}
{{ dump(var.bar|default(true)) }}
{# expected true, got true #}
{{ dump(var.baz|default(true)) }}
About this issue
- Original URL
- State: closed
- Created 12 years ago
- Reactions: 4
- Comments: 23 (11 by maintainers)
Commits related to this issue
- Fix(web-twig): Default filter is not working as expected for false value * @see: https://github.com/twigphp/Twig/issues/769 * @see: https://twig.symfony.com/doc/2.x/filters/default.html * last ... — committed to lmc-eu/spirit-design-system by literat a year ago
- Fix(web-twig): Default filter is not working as expected for false value * @see: https://github.com/twigphp/Twig/issues/769 * @see: https://twig.symfony.com/doc/2.x/filters/default.html * last ... — committed to lmc-eu/spirit-design-system by literat a year ago
- Fix(web-twig): Default filter is not working as expected for false value * @see: https://github.com/twigphp/Twig/issues/769 * @see: https://twig.symfony.com/doc/2.x/filters/default.html * last ... — committed to lmc-eu/spirit-web-twig-bundle by literat a year ago
You can use this workaround for this problem.
Here’s an example: http://twigfiddle.com/ziwbxt Select “Set as main template” for child2.twig as well and see the difference in the output on the right.
The catch is that the variable you’re testing must be defined with
{% set %}in the main template.EDIT: You don’t really have to predefine variables in the main template, you can just use the null-coalescing operator inline.
this is not specific to arrays:
And this is what is documented: the doc says the default will be applied for undefined or empty values. And
falseis considered as an empty value.should really be changed. just wasted time to debug. this is really counterintutive. php gets stricter and stricter and twig is doing the oposite
this is so counterintuitive and dumb - $0.02
One more vote for not triggering the ‘default’ filter on FALSE but only on NULL or UNDEF
I suggest to close here. The suggested change would be a BC break, there already is the
??operator and noone seemed to be interested in updating the docs for thedefinedtest.@stof “I’m never quite so stupid as when i’m being smart”. Point taken. Maybe it would be worth mentioning the ‘??’ operator in the doc. page for ‘default’ ?
@gggeek but then, that would be exactly the
??operator (but slower as it could not always be identified as such at compile time and be replaced by the??operator which compiles to faster code when it can use the PHP??operator)