覆盖的Twig模板中覆盖块

覆盖的Twig模板中覆盖块

有没有一个普遍的“好”的方式来实现这个功能? 我已经阅读了关于'use'的标签,这似乎是迄今为止最好的选择,但我仍然不喜欢它,它不会让我带来任何外部的html,只有块。

我将在下面的示例中使用'include'标签来演示我想要描述的意图。

#base.html.twig
{% include 'elements/header.html.twig' %}
{% block content %}{% endblock %}
{% include 'elements/footer.html.twig' %}

#header.html.twig
<h1>This is my header</h1>
{% block page_title %} Default Page Title {% endblock %}

#index.html.twig
{% extends 'layouts/base.html.twig' %}
{# I want to be able to do this somehow #}
{% block page_title %} This is my overridden page title {% endblock %}
{% block content %} here is the index page content {% endblock %}
采纳答案:

我找到了一个解决方案 使用block()函数来获取小孩的块内容,并将其作为include语句中的变量传递给header.html.twig:

#base.html.twig
{% include 'elements/header.html.twig' with {page_title: block('page_title')} %}
{% block content %}{% endblock %}
{% include 'elements/footer.html.twig' %}

#header.html.twig
<h1>This is my header</h1>
{% if page_title is empty %}
Default Page Title
{% else %}
{{ page_title }}
{% endif %}

#index.html.twig
{% extends 'layouts/base.html.twig' %}
{% block page_title %} This is my overridden page title {% endblock %}
{% block content %} here is the index page content {% endblock %}

参考更多解答:覆盖的Twig模板中覆盖块,转载请保留覆盖的Twig模板中覆盖块

更多:php