Django 模板:为什么包含模板中的块不能被子模板覆盖?

发布于 2024-09-28 09:17:59 字数 666 浏览 4 评论 0原文

为了更清楚地说明我的问题,让我们假设我有一个包含内容的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎夜雨 2024-10-05 09:17:59

当您包含模板时,它会呈现该模板,然后包含呈现的内容。

来自 django 文档:

include 标签应被视为“呈现此子模板并包含 HTML”的实现,而不是“解析此子模板并包含其内容,就好像它是父模板的一部分一样”。这意味着包含的模板之间没有共享状态——每个包含都是一个完全独立的渲染过程。

解决方法是让子模板扩展包含模板而不是包含模板。然后,包含子模板。

When you include a template, it renders the template, then includes the rendered content.

From the django docs:

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

A workaround would be to have the child template extend the included template instead of the including template. Then, include the child template.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文