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 %}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With