你如何在带有树枝的嵌入中引用父范围?

How do you reference the parent scope in an embed with twig?

我想在模板中添加一个可以被子模板覆盖的块。问题是我想把这个块放在一个嵌入中,它有自己的范围。

有谁知道如何使用嵌入式模板指定工作范围?

{# base.html.twig #}

{% embed "AcmeBundle:component.html.twig" %}
  {% block header %}
    <h2>Foo!!</h2>
  {% endblock %}

  {% block content %}
    {% block content_set_by_child %}{% endblock %}
  {% endblock %}
{% endembed %}
{# child.html.twig #}

{% extends "base.html.twig" %}

{% block content_set_by_child %}
  <p>Bar!!</p>
{% endblock %}

似乎嵌入创建了一个新的块作用域,因此您不能在父模板中覆盖它们。为了解决这个问题,我使用了 set 似乎可以访问父范围。

{# main.html.twig #}

{% extends "base.html.twig" %}

{% set inner_html %}
  <p>Bar!!</p>
{% enset %}
{# base.html.twig #}

{% embed "AcmeBundle:component.html.twig" %}
  {% block header %}
    <h2>Foo!!</h2>
  {% endblock %}

  {% block content %}
    {{ inner_html }}
  {% endblock %}
{% endembed %}

Pre-fix fiddle

Post-fix fiddle