with
使用 with
标签创建一个新的内部作用域。在此作用域内设置的变量在作用域外不可见
1 2 3 4 5
{% with %}
{% set value = 42 %}
{{ value }} {# value is 42 here #}
{% endwith %}
value is not visible here any longer
您无需在作用域的开头定义变量,而是可以传递您想要在 with
标签中定义的变量映射;之前的示例等同于以下示例
1 2 3 4 5 6 7 8 9 10
{% with {value: 42} %}
{{ value }} {# value is 42 here #}
{% endwith %}
value is not visible here any longer
{# it works with any expression that resolves to a mapping #}
{% set vars = {value: 42} %}
{% with vars %}
...
{% endwith %}
默认情况下,内部作用域可以访问外部作用域上下文;您可以通过附加 only
关键字来禁用此行为
1 2 3 4 5
{% set zero = 0 %}
{% with {value: 42} only %}
{# only value is defined #}
{# zero is not defined #}
{% endwith %}