Template inheritance and duplicated content.

115 views
Skip to first unread message

Jonathan Slenders

unread,
May 24, 2011, 4:58:25 AM5/24/11
to Django developers
Hi all,

This seems like a weirdness in template inheritance...

base.html

{% block title %} ... {% endblock %}
{% block content %}... {% endblock %}


index.html
{% extends "base.html" %}
{% block content %}
{% block title %}
<p>some text</p>
{% endblock %}
{% endblock %}


The paragraph is shown twice in the output. Once, because the block
'title' is copied into the 'title' of the parent during the
inheritance, and once because the block 'content' is copied.

I guess this is a flaw in the inheritance algorithm, only the most
outer blocks should be used during the resolving of inheritance.

Because: if we would extend index.html, and override the block
"title", the current template engine will replace the title-block from
base.html, instead of the nested title-block of index.html which is
completely counter-intuitive.

Is this behaviour documented or on purpuse? We should have a clear
definition of how inheritance should work, especially now the Jinja-
guy is working on a compatible template engine. (And also the template
preprocessor does resolve inheritance at compile time.)

It is otherwise possible that people will start using this flaw as a
kind of macro-feature, to intentionally duplicate content.

Jonathan


Jonathan Slenders

unread,
May 24, 2011, 5:10:57 AM5/24/11
to Django developers
Even more confusing, but extremely great to abuse!


base.html
{% block a %}{% endblock %}
{% block b %}{% endblock %}
{% block c %}{% endblock %}
{% block d %}{% endblock %}
{% block e %}{% endblock %}

index.html
{% block a %}
{% block b %}
{% block c %}
{% block d %}
{% block e %}
duplicate
{% endblock %}
{% endblock %}
{% endblock %}
{% endblock %}
{% endblock %}


This will print "duplicate", 5 times, and cover cases that a for-loop
can't because all the different blocks in base.html can be spread over
the whole template, whereever you want. :)

Armin Ronacher

unread,
Jun 9, 2011, 7:49:33 AM6/9/11
to Django developers
Hi,


On May 24, 10:58 am, Jonathan Slenders <jonathan.slend...@gmail.com>
wrote:
> I guess this is a flaw in the inheritance algorithm, only the most
> outer blocks should be used during the resolving of inheritance.
How else would it work? Think of a block like a function plus the
execution of that function. By placing a new block within a block you
want that behavior and if you override a block and in that another
block that already existed both Jinja2 and Django will have to also
immediately call it. There is only one rule: if you don't like that,
make the block toplevel. The only alternative sane semantic would be
raising a runtime error, but I don't think that is a good idea.

Regards,
That Jinja guy
Reply all
Reply to author
Forward
0 new messages