[英]Twig default filter overrides defined template variables?
I have the following construction in twig templates to create XML: 我在树枝模板中具有以下构造以创建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>
As you can see the two template partials include each other by default ( {% if dOptions|default(true) %}
and {% if dInsurances|default(true) %}
). 如您所见,两个模板部分在默认情况下彼此包括(
{% if dOptions|default(true) %}
和{% if dInsurances|default(true) %}
)。 If not stopped properly it will cause an infinite loop and the application breaks with a maximum nested level fatal error. 如果未正确停止,将导致无限循环,并且应用程序将中断,并出现最大嵌套级别的致命错误。
When partial optionNode is included in insuranceNode, the template var dInsurances
is set to false which should set the var dInsurances
in optionNode to false. 当部分optionNode包含在insuranceNode中时,模板var
dInsurances
设置为false,这应将dInsurances
中的var dInsurances
设置为false。 Yet for some reason optionNode still prefers the default(true) for dInsurances
over the template variable set by insuranceNode. 但是由于某种原因,optionNode仍然比
dInsurances
设置的模板变量更喜欢dInsurances的default(true)。
If the default() filter is removed from dInsurances
in the optionNode, it works as expected. 如果从
dInsurances
中的dInsurances中删除了default()过滤器,则该过滤器将按预期工作。 Also when dInsurances
is set to true, it crashes as expected. 同样,当
dInsurances
设置为true时,它dInsurances
按预期崩溃。
Am I misunderstanding the mechanics of the default() filter? 我是否误解了default()过滤器的机制? Or should the variable passed through the include directive be inherited in the template?
还是应该通过include指令传递的变量在模板中继承?
Any help is much appreciated. 任何帮助深表感谢。 Thanks in advance :)
提前致谢 :)
From Twig documentation: 从Twig文档中:
The default filter returns the passed default value if the value is undefined or empty, otherwise the value of the variable
如果值未定义或为空,则默认过滤器返回传递的默认值,否则返回变量的值
So, if you pass false, twig will take default value. 因此,如果您传递假值,树枝将采用默认值。
There are 2 fixes: 有2个修复程序:
Use "not" with negative values 对负值使用“ not”
{% if not skipOptions %} ... 'skipInsurances': true
Use "defined" test: http://twig.sensiolabs.org/doc/tests/defined.html 使用“定义的”测试: http : //twig.sensiolabs.org/doc/tests/defined.html
{% if dOptions is not defined or dOptions %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.