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

标签 python django templates include extend

为了更清楚地说明我的问题,假设我有一个包含内容的 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/

相关文章:

python - tkinter 调用 tk.canvas.create_window() 时什么是窗口

python - 如何在 Vim 中拉出整个 block ?

python - 在 django CreateView 中将 args 和 kwargs 传递给具有额外内容的父类

c++ - 如何确定一个类是否包含子类/类型?

c++ - 打印返回的迭代器

python - 如何在Python中正确处理记录器文件大小?

python - tf.contrib.layers.sparse_column_with_integerized_feature 可以处理一列中具有多个输入的分类特征吗?

python - Mac 上的 Django 和 mysql

python - 无法使用_set查询外键相关对象| Django ?

c++ - 可变参数构造函数优先于用户提供的 move 构造函数,默认情况下除外