Overriding blocks within included Twig templates

前端 未结 5 942
北荒
北荒 2020-12-12 21:19

Is there a generally \"good\" way to achieve this functionality? I have read about the \'use\' tag, which seems like the best option so far, but I still don\'t like that it

5条回答
  •  -上瘾入骨i
    2020-12-12 22:02

    Improvement on @webberig's solution, that fixes blocks that are not overridden in all extending templates (comment by @HerrNentu'):

    #base.html.twig
    {% if block("page_title") is defined %}
         {% include 'elements/header.html.twig' with {page_title: block('page_title')} %}
    {% else %}
         {% include 'elements/header.html.twig' with {page_title: null} %}
    {% endif %}
    {% block content %}{% endblock %}
    {% include 'elements/footer.html.twig' %}
    
    #header.html.twig
    

    This is my header

    {% 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 %}

提交回复
热议问题