带有“默认"的错误Twig/Symfony 2 中的过滤器和布尔宏参数? [英] Bug with "default" filter and boolean macro arguments in Twig / Symfony 2?
问题描述
我正在使用 default
Twig 过滤器在我的 macro 中指定参数默认值:
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 %}
问题是dismissable
参数类型应该是boolean
.但是,当传递 false
时,过滤器会对其进行评估并分配一个 true
默认值.示例输出:
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.
布尔值 false
的评估甚至没有被提及.我的临时解决方法是:
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:
如果值未定义或空
我的重点.False 是一个空值.
Emphasis by me. False is an empty value.
Twig_Node_Expression_Default 创建代码中的 Twig_Node_Expression_Conditional.最后,默认过滤器归结为以下 php 代码:
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
在您的情况下,传递的值为 false,因此表达式返回默认值.
In your case the passed value is false, so the expression returns the default value.
您应该继续使用您的解决方法.
You should keep using your workaround.
这篇关于带有“默认"的错误Twig/Symfony 2 中的过滤器和布尔宏参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!