【问题标题】:Django - Block tags in included templates get overridden by calling templateDjango - 包含模板中的块标签通过调用模板被覆盖
【发布时间】:2023-12-04 08:09:02
【问题描述】:

我有一个包含另一个模板的模板。这个包含的模板中有块标签。

例子:

base.html

BASE
{% block title %}Base Title{% endblock %}
{% block content %}{% endblock %}

模板1.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 中的标题块,则不会发生这种情况。在我看来,它同时包含和扩展?任何人都知道这是否是预期的/我做错了什么?

【问题讨论】:

    标签: django include block extends overriding


    【解决方案1】:

    如果您没有在include.html 中使用 extends,那么这种行为是正常的 - 我想 1.1.1 中存在错误。

    摘自官方文档:

    最后要注意,不能在同一个模板中定义多个同名的 {% block %} 标签。存在此限制是因为块标签在“两个”方向上工作。也就是说,块标签不仅提供了一个要填充的洞——它还定义了填充父级洞的内容。如果模板中有两个名称相似的 {% block %} 标记,则该模板的父级将不知道要使用哪个块的内容。

    在这里阅读全文:Template Inheritance

    【讨论】:

      【解决方案2】:

      如果这是你想要的,那么 include.html 根本不应该包含任何块,即:

      Include Title
      Include Content
      

      【讨论】:

      • 这有点像我上面所说的:)