在Twig中的其他块中显示设置变量

时间:2013-07-14 11:04:45

标签: variables twig

{% block someBlock %}
{% set foo = 'blah blah blah' %}
{% endblock %}

{% block otherBlock %}
{{ foo }}
{% endblock %}

这不能按预期工作(foo在第二个块中不可见)。如何使其全局可见并使其按预期工作?

2 个答案:

答案 0 :(得分:1)

似乎是TWIG或Symfony2问题:

https://github.com/fabpot/Twig/issues/735

也许在不久的将来......

答案 1 :(得分:0)

必须在外部范围内初始化

foo

{# begin template "foo.html" #}

{% set foo = 'default value' %}  {# defined bar.foo #}

{% block someBlock %}
{% set foo = 'blah blah blah' %} {# changes bar.foo #}
{{ foo }}                        {# outputs bar.foo #}
{% set baz = 'other' %}          {# defined #}
{% endblock %}

{% block otherBlock %}
{{ foo }}                        {# outputs bar.foo #}
{{ baz }}                        {# undefined #}
{% endblock %}

{# template "main.html" #}

{% include "foo.html" as bar %}

{{ block('someBlock') }}
{{ block('otherBlock')}}