简体   繁体   中英

Twig: How to show block inside include template

I have this structure of template files:

   {# layout.html #}

    <!DOCTYPE HTML>
    <html lang="pt-br">
    <head>
       <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="UTF-8">
       <title>Twig Project</title>
    </head>

    <body>
      <div id="content">
         {% block body %} {% endblock body %}
      </div>
      <div id="footer"> 
         {% block footer %} {% endblock footer %}
      </div>
    </body>
   </html>

----------

{# specialpage.html #}

Especial content

{% block footer %} THIS IS A SPECIAL FOOTER {% endblock footer %}

----------

{# page1.html #}

{% extends "layout.html" %}

{% include 'specialpage.html' %}

Problem: When I include the "specialpage.html" the "block footer" with the mesage "THIS IS A SPECIAL FOOTER" not display. Why?

I have been struggling with the same problem. I was hoping the include tag for Twig would first insert the content of the included template, and then parse the entire content, effectively replacing blocks in the extended page (layout) when these are referenced from the included page (specialpage).

But instead, I have come to believe that the include tag parses the included template first, and inserts the parsed content of the included template, before parsing the parent page.

The documentation says the include tag includes templates with inheriting the parent scope. But it seems this is only true for variables, not for defined blocks. I assume you can not override blocks in parent pages or parent layouts from within included templates.

I think my solution lies in rewriting my layout templates to make as much use of the 'extends' tag as I can, for this tag seems to be critical in enabling the desired inheritance structure.

While I will rewrite my templates and assume you should, too, I have a small amount of hope that we're doing it wrong, and someone will come along with the right way to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM