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

Most upvoted comments

You can use this workaround for this problem.

{# main.twig #}
{% set var = var ?? false %}

{% if var %}
    <span>I'm special!</span>
{% endif %}
{# child1.twig #}
{% extends "main.twig" %}
{% set var = true %}
{# child2.twig #}
{% extends "main.twig" %}

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.

{# main.twig #}

{% if (var ?? false) %}
    <span>I'm special!</span>
{% endif %}

this is not specific to arrays:

{% set foo = false %}
{{ dump(foo|default(true)) }}
{# got true #}

And this is what is documented: the doc says the default will be applied for undefined or empty values. And false is 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 the defined test.

@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)