On 7/28/05, Andy Gimblett <
g...@gimbo.org.uk> wrote:
> I don't seem to be able to include multiple instances of a
> particularly named block within a template. Doing so seems to raise a
> TemplateSyntaxError (django/core/template_loader.py, line 111, in
> do_block).
>
> Is there a good reason for this other than sanity checking? If it's
> just a sanity check, then I'd like to argue for it being unnecessary
> and over-restrictive. I'd like, for example, to use a block called
> "title" in both the <title> part of my page, and in an <h1> at the
> top. Isn't that reasonable? I'd expect the behaviour to be "wherever
> you see this block, fill it in with the supplied value", really. But
> maybe I'm missing some reason why this is a bad idea.
Hey Andy,
The reason you can't have two {% block %}s in the same template is
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.
For example, say this is your parent template, "base":
"""
<html>
<head><title>{% block title %}{% endblock %}</title></head>
<body>
{% block content %}{% endblock %}
</body>
</html>
"""
And here's the child template:
"""
{% extends "base" %}
{% block title %}Foo{% endblock %}
{% block title %}Bar{% endblock %}
{% block content %}Here's the content{% endblock %}
"""
In this case, the template rendering engine wouldn't know which {%
block title %} to put in the parent template. That's the problem.
Of course, this is only a problem when a *child* template defines two
blocks -- it's not a problem when a parent template defines two
blocks. (In the latter case, it can be useful, as you've pointed out.)
I suppose it would be possible to change the template system's
behavior to allow for duplicate block names only within top-level
*parent* templates...but is the complexity worth the special-case? I'd
love to hear people's opinions on this.
At any rate, thanks for bringing this up!
Adrian