with
¶
使用 with
创建一个新的内部范围。在此范围内设置的变量在范围外不可见:
1 2 3 4 5 | {% with %}
{% set foo = 42 %}
{{ foo }} {# foo is 42 here #}
{% endwith %}
foo is not visible here any longer
|
可以传递要在 with
tag;上一个示例与下面的示例等效:
1 2 3 4 5 6 7 8 9 10 | {% with { foo: 42 } %}
{{ foo }} {# foo is 42 here #}
{% endwith %}
foo is not visible here any longer
{# it works with any expression that resolves to a hash #}
{% set vars = { foo: 42 } %}
{% with vars %}
...
{% endwith %}
|
默认情况下,内部作用域可以访问外部作用域上下文;可以通过附加 only
关键字:
1 2 3 4 5 | {% set bar = 'bar' %}
{% with { foo: 42 } only %}
{# only foo is defined #}
{# bar is not defined #}
{% endwith %}
|