Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

twig

symfony

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 falsethe 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 %}
like image 572
gremo Avatar asked May 28 '12 22:05

gremo


2 Answers

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.

like image 80
Maerlyn Avatar answered Oct 16 '22 13:10

Maerlyn


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.

like image 30
Jeppe Hasseriis Avatar answered Oct 16 '22 12:10

Jeppe Hasseriis