Reputation: 48487
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 %}
Upvotes: 7
Views: 3661
Reputation: 1072
This is the expected behaviour as @Maerlyn already mentioned.
But you can take advantage of the fallback
filter and simplify a bit your code.
This will work:
{% set dismissable = dismissable|fallback(true) %}
Upvotes: 0
Reputation: 310
You can use the null-coalescing operator ??
like this:
{% set dismissable = dismissable ?? true %}
That should solve your problem and it's a nice and clean solution. :-)
EDIT: It also solves the default(false)
problem.
Upvotes: 5
Reputation: 31
A replacement for the problematic expression my_boolean|default(true)
(my_boolean|default(false)
works as expected), can be not my_boolean is defined or my_boolean
.
Upvotes: 3
Reputation: 620
I faced the same "problem" and I did like this:
{% set dismissable = dismissable is not same as(false) %}
Upvotes: 1
Reputation: 34125
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.
Upvotes: 16