gpt4 book ai didi

python - Django 模板 : Why block in included template can't be overwritten by child template?

转载 作者:太空狗 更新时间:2023-10-29 18:03:25 25 4
gpt4 key购买 nike

为了更清楚地说明我的问题,假设我有一个包含内容的 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。但是好像不能。为什么?有解决方法吗?

最佳答案

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

来自 django 文档:

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.

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

关于python - Django 模板 : Why block in included template can't be overwritten by child template?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3983872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com