Django - 通过调用模板来覆盖包含模板中的块标签
我有一个模板,其中包含另一个模板。此包含的模板中包含块标签。
示例:
base.html
BASE
{% block title %}Base Title{% endblock %}
{% block content %}{% endblock %}
template1.html
{% extends 'base.html' %}
{% block title %}Extended Title{% endblock %}
{% block content %}
Extended content
{% include 'include.html' %}
{% endblock %}
include.html
{% block title %}Include Title{% endblock %}
{% block another_content %}Include Content{% endblock %}
我期望的是,如果我渲染 template.html 我应该得到,这是我在 1.1.1 下所做的
BASE
Extended Title
Extended content
Include Title
Include Content
但是当我切换到 1.2.1 和 1.2.3 时我实际上得到了这个:
BASE
Extended Title
Extended Content
Extended Title
Include Content
如您所见,include.html 中的标题块被 template1.html 的标题块替换。仅当块名称相同时才会发生此替换,因此如果我更改 include.html 中的标题块,则不会发生这种情况。在我看来,它是同时包含和延伸的?有人知道这是否是预期的/我做错了什么?
I have a template that includes another template. This included template has block tags in it.
Example:
base.html
BASE
{% block title %}Base Title{% endblock %}
{% block content %}{% endblock %}
template1.html
{% extends 'base.html' %}
{% block title %}Extended Title{% endblock %}
{% block content %}
Extended content
{% include 'include.html' %}
{% endblock %}
include.html
{% block title %}Include Title{% endblock %}
{% block another_content %}Include Content{% endblock %}
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
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您在
include.html
中未使用extends
,那么这种行为是正常的 - 我认为 1.1.1 中存在错误。摘自官方文档:
在这里阅读全文:模板继承
If you're not using
extends
ininclude.html
then this behaviour is normal - I suppose that there was a bug in 1.1.1.Excerpt from official documentation:
Read whole thing here: Template Inheritance
如果这就是您想要的,那么 include.html 根本不应该包含任何块,即:
If that's what you want, then the include.html should not contain any blocks at all, ie just: