Twig默认过滤器会覆盖定义的模板变量吗?

Ber*_*oet 2 php xml symfony twig

我在twig模板中有以下构造来创建XML:

{# insuranceNode.xml.twig #}
<insurance>
    <description></description>
    ...

    {% if dOptions|default(true) %}
    <options>
        {% for option in insurance.options %}
        {% include 'optionNode.xml.twig' with {
            'option': option,
            'dInsurances': false
        }%}
        {% endfor %}
    </options>
    {% endif %}

</insurance>

{# optionNode.xml.twig #}
<option>
    <description></description>
    ...

    {% if dInsurances|default(true) %}
    <insurances>
        {% for insurance in option.insurances %}
        {% include 'insuranceNode.xml.twig' with {
            'insurance': insurance,
            'dOptions': false
        }%}
        {% endfor %}
    </insurances>
    {% endif %}

</options>
Run Code Online (Sandbox Code Playgroud)

如您所见,默认情况下({% if dOptions|default(true) %}{% if dInsurances|default(true) %})两个模板部分相互包含.如果没有正确停止,它将导致无限循环,并且应用程序因最大嵌套级别致命错误而中断.

当保险节点中包含部分optionNode时,模板var dInsurances设置为false,应将dInsurancesoptionNode中的var设置为false.但由于某种原因,optionNode仍然更喜欢dInsurances由insuranceNode设置的模板变量的默认值(true).

如果从dInsurancesoptionNode中删除了default()过滤器,它将按预期工作.此外,当dInsurances设置为true时,它会按预期崩溃.

我误解了default()过滤器的机制吗?或者,通过include指令传递的变量是否应该在模板中继承?

任何帮助深表感谢.提前致谢 :)

Mar*_*tis 7

来自Twig文档:

如果值未定义或为空,则默认过滤器返回传递的默认值,否则返回变量的值

因此,如果您传递false,twig将采用默认值.

有2个修复:

  1. 使用带有负值的"not"

    {% if not skipOptions %}
    ...
    'skipInsurances': true
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用"已定义"测试:http://twig.sensiolabs.org/doc/tests/defined.html

    {% if dOptions is not defined or dOptions %}
    
    Run Code Online (Sandbox Code Playgroud)

  • 默认过滤器归结为此代码:`$ passed_value?$ passed_value:$ default_value`,这就是为什么当传递false时它使用默认值而不是传递的值. (2认同)