简体   繁体   English

在Twig / Symfony 2中使用“默认”过滤器和布尔宏参数的错误?

[英]Bug with “default” filter and boolean macro arguments in Twig / Symfony 2?

I'm using default Twig filter to specify arguments defaults in my macro : 我正在使用default Twig过滤器来指定我的宏中的参数默认值:

{% 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 . 问题dismissable参数类型应该是boolean However when passing false the filter evaluates it and assign a true default value. 但是,当传递false ,过滤器会对其进行求值并指定一个true默认值。 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. 甚至没有提到布尔false评估。 My temporary workaround is: 我的临时解决方法是:

{% set dismissable = dismissable is not defined or dismissable is null ?
    true : dismissable %}

It is not a bug. 这不是一个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. False是一个空值。

Twig_Node_Expression_Default creates a Twig_Node_Expression_Conditional in the code. Twig_Node_Expression_Default在代码中创建Twig_Node_Expression_Conditional In the end the default filter boiles down to the following php code: 最后,默认过滤器归结为以下php代码:

$passed_value ? $passed_value : $default_value

In your case the passed value is false, so the expression returns the default value. 在您的情况下,传递的值为false,因此表达式返回默认值。

You should keep using your workaround. 您应该继续使用您的解决方法。

替换有问题的表达式my_boolean|default(true)my_boolean|default(false)按预期工作),可以not my_boolean is defined or my_boolean

我遇到了同样的“问题”,我确实喜欢这样:

{% set dismissable = dismissable is not same as(false) %}

You can use the null-coalescing operator ?? 你可以使用null-coalescing运算符?? 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. 编辑:它还解决了default(false)问题。

This is the expected behaviour as @Maerlyn already mentioned. 这是@Maerlyn已经提到过的预期行为。
But you can take advantage of the fallback filter and simplify a bit your code. 但是您可以利用fallback过滤器并简化代码。
This will work: 这将有效:
{% set dismissable = dismissable|fallback(true) %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM