Blocks in included files not being filled by extended templates

淺唱寂寞╮ 提交于 2020-01-15 03:07:20

问题


I have a template that looks like this:

{% include "base/top.html" with context %}
{% include "base/nav.html" with context %}
<div id="content">
    Stuff
    {% block content %}{% endblock %}
</div>
{% include "base/bottom.html" with context %}

base/nav.html and base/bottom.html contain static content, but base/top.html contains a {% block title %}. So when I have a second template as that attempts to inherit from the first file like so:

{% extends firstfile.html %}
{% block title %}Imarealpage!{% endblock %}
{% block content %}Lorem ipsum dorem smitshm{% endblock %}

The {% block title %} section isn't rendered. How do ensure that it, and any other blocks in included files and defined in extended templates are rendered as they should be?


回答1:


You're misunderstanding how {% include %} works. The {% include %} tag is not a pre-processor; it doesn't plop the included template's code directly into the including template before rendering. Instead, {% include %} fires off a new independent template render of the included template (just like as if you had rendered the included template directly from your own code), and then includes the rendered results into the rendering of the included template.

The implication of this is that included templates have a totally separate inheritance hierarchy from their including template. You can, for instance, have a base component.html template with some blocks in it, and then have e.g. foo-component.html which starts with {% extends "component.html" %} and fills in some blocks from component.html. And then you can have a layout.html that does {% include "foo-component.html" %}, and that will render foo-component.html, complete with its inheritance of component.html, and place the result into that spot in layout.html. But there is zero relationship between any blocks in layout.html and any blocks in component.html -- they are separate renders with separate block structures and inheritance hierarchies.



来源:https://stackoverflow.com/questions/15058974/blocks-in-included-files-not-being-filled-by-extended-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!