开发者

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

开发者 https://www.devze.com 2023-01-17 09:38 出处:网络
I have a template that includes another template.This included template has block tags in it. Example:

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 Cont开发者_JAVA技巧ent

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?


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


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

Include Title
Include Content
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号