Django - Block tags in included templates get overridden by calling template

▼魔方 西西 提交于 2019-12-11 00:08:10

问题


I have a template that includes another template. This included template has block tags in it.

Example:

base.html

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

template1.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 %}

What I'm expecting is if I render template.html I should get, which I do under 1.1.1

BASE
Extended Title
Extended content
Include Title
Include Content

But I actually get this when I switched to 1.2.1 and 1.2.3:

BASE
Extended Title
Extended Content
Extended Title
Include Content

As you can see, the title block in include.html gets replaced with template1.html's title block. This replacement only happens if the block names are the same, so if I change the title block in include.html, this doesnt occur. It seems to me that it's including and extending at the same time? Anyone know if this is expected/I'm doing something wrong?


回答1:


If you're not using extends in include.html then this behaviour is normal - I suppose that there was a bug in 1.1.1.

Excerpt from official documentation:

Finally, note that you can't define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill -- it also defines the content that fills the hole in the parent. If there were two similarly-named {% block %} tags in a template, that template's parent wouldn't know which one of the blocks' content to use.

Read whole thing here: Template Inheritance




回答2:


If that's what you want, then the include.html should not contain any blocks at all, ie just:

Include Title
Include Content


来源:https://stackoverflow.com/questions/3796462/django-block-tags-in-included-templates-get-overridden-by-calling-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!