Django 模板:为什么包含模板中的块不能被子模板覆盖?
为了更清楚地说明我的问题,让我们假设我有一个包含内容的 include.html 模板:
{% block test_block %}This is include{% endblock %}
我有另一个名为parent.html 的模板,其内容如下:
This is parent
{% include "include.html" %}
现在我创建一个名为 child.html 的模板,它扩展了parent.html:
{% extends "parent.html" %}
{% block test_block %}This is child{% endblock %}
我的想法是渲染child.html时,child.html中的test_block可以覆盖include.html中的test_block。根据我的理解,当包含模板时,它会按原样包含。所以就我而言,我认为parent.html等于:
This is parent
{% block test_block %}This is include{% endblock %}
所以child.html应该能够覆盖test_block。但貌似不能。为什么?有解决方法吗?
To illustrate my question more clearly, let's suppose I have a include.html template with content:
{% block test_block %}This is include{% endblock %}
I have another template called parent.html with content like this:
This is parent
{% include "include.html" %}
Now I create a templated called child.html that extends parent.html:
{% extends "parent.html" %}
{% block test_block %}This is child{% endblock %}
My idea is that when rendering child.html, the test_block in child.html can overwrite the one in include.html. As per my understanding, when a template is included, it is included as it is. So in my case, I think parent.html equals to:
This is parent
{% block test_block %}This is include{% endblock %}
So child.html should be able to overwrite test_block. But looks like it can't. Why? Is there a workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您包含模板时,它会呈现该模板,然后包含呈现的内容。
来自 django 文档:
解决方法是让子模板扩展包含模板而不是包含模板。然后,包含子模板。
When you include a template, it renders the template, then includes the rendered content.
From the django docs:
A workaround would be to have the child template extend the included template instead of the including template. Then, include the child template.