Bug with "default" filter and boolean macro arguments in Twig / Symfony 2?

symfony, twig

Solution

It is not a bug. The docs you quoted mentions it, though it's far from being obvious:

if the value is undefined or empty

Emphasis by me. False is an empty value.

Twig_Node_Expression_Default creates a Twig_Node_Expression_Conditional in the code. In the end the default filter boiles down to the following php code:

$passed_value ? $passed_value : $default_value

In your case the passed value is false, so the expression returns the default value.

You should keep using your workaround.

Problem

I'm using `default` Twig filter to specify arguments defaults in my macro: ``` {% macro base(type, title, content, separator, dismissable) %} {% spaceless %} {% debug dismissable %} {% set separator = separator|default('!') %} {% set dismissable = dismissable|default(true) %} {% debug dismissable %} {# Beginning outputting... #} {% endspaceless %} {% endmacro %} ``` The problem is that `dismissable` argument type should be `boolean`. However when passing `false`the filter evaluates it and assign a `true` default value. An example output: ``` {{ base('success', 'Title', 'Hello', '!', false) }} boolean false boolean true ``` Is this a bug? Here is (part of) filter description: The default filter returns the passed default value if the value is undefined or empty, otherwise the value of the variable. Evaluation of boolean `false` is not even mentioned. My temporary workaround is: ``` {% set dismissable = dismissable is not defined or dismissable is null ? true : dismissable %} ```

Original source