Django - 调用模板会覆盖包含模板中的块标记 [英] Django - Block tags in included templates get overridden by calling template
问题描述
我有一个包含另一个模板的模板。这个包含的模板中有块标签。
I have a template that includes another template. This included template has block tags in it.
示例:
base.html
base.html
BASE
{% block title %}Base Title{% endblock %}
{% block content %}{% endblock %}
template1.html
template1.html
{% extends 'base.html' %}
{% block title %}Extended Title{% endblock %}
{% block content %}
Extended content
{% include 'include.html' %}
{% endblock %}
include.html
include.html
{% block title %}Include Title{% endblock %}
{% block another_content %}Include Content{% endblock %}
如果我渲染template.html,我期待的是我应该得到,我在1.1.1下做。
What I'm expecting is if I render template.html I should get, which I do under 1.1.1
BASE
Extended Title
Extended content
Include Title
Include Content
但是当我切换到1.2时,我实际上得到了这个。 1和1.2.3:
But I actually get this when I switched to 1.2.1 and 1.2.3:
BASE
Extended Title
Extended Content
Extended Title
Include Content
如您所见,include.html中的标题栏被替换为template1.html的标题栏。仅当块名称相同时才会发生此替换,因此如果我更改include.html中的标题块,则不会发生这种情况。在我看来,它同时包括和延伸?任何人都知道这是否是预料/我做错了什么?
As you can see, the title block in include.html gets replaced with template1.html's title block. This replacement only happens if the block names are the same, so if I change the title block in include.html, this doesnt occur. It seems to me that it's including and extending at the same time? Anyone know if this is expected/I'm doing something wrong?
推荐答案
如果你没有使用 在
然后这种行为是正常的 - 我想1.1.1中有一个错误。 include.html
中扩展
If you're not using extends
in include.html
then this behaviour is normal - I suppose that there was a bug in 1.1.1.
摘自官方文件:
最后,请注意你可以'在同一模板中定义多个具有相同名称的{%block%}标记。存在这种限制是因为块标签在两个方向上工作。也就是说,块标记不仅提供填充孔 - 它还定义填充父级孔的内容。如果模板中有两个同名的{%block%}标记,则该模板的父级将不知道要使用哪个块的内容。
Finally, note that you can't define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill -- it also defines the content that fills the hole in the parent. If there were two similarly-named {% block %} tags in a template, that template's parent wouldn't know which one of the blocks' content to use.
在这里阅读整篇文章:模板继承
Read whole thing here: Template Inheritance
这篇关于Django - 调用模板会覆盖包含模板中的块标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!