views:

57

answers:

2

I have a structure where there's normally a page heading in (% block heading %} in my base template:

base.html

<h2>{% block heading %}{% endblock %}</h2>

Most of the time, I'll pass in a heading like this through templates that extend base:

extends-base.html

{% block heading %}Super Cool Page!{% endblock %}

However, for a special page, I don't want to have a page heading:

extends-base-special.html

{% block heading %}{% endblock %}

Ideally, this should exclude the <h2> tags. Now, I could just make the all of the extending templates include the <h2> tags, but that violates DRY, as every page should have the same element for the page-level heading. What I'd prefer to do is this (which doesn't appear to work):

base-prefered.html

{% if heading %}
<h2>{% block heading %}{% endblock %}</h2>
{% endif %}

Is this doable somehow on the template level, or do I have to tuck into views for this?

+1  A: 

Do it like this:

  • base.html - whole structure <h2>{% block heading %}{% endblock %}</h2>
  • base-without-heading.html - extend base with this {% block heading %}{% endblock %}

And then either extend the first or the second template. I believe this should be the easiest way.

And by the way. By writing:

{% if heading %}

you are actuallly asking for boolean value of element in the context with name 'heading'. Elements of django markup language arent held in the context, so you can't ask for them. You could write a tag, that adds something to the context, I once needed such thing and used it, but I don't believe that's the way to go here. Above solution should work (I don't have machine to check this) and it's the best way IMNSHO.

gruszczy
No good. You get an empty `<h2>` tag on the page.
CommanderVoms
+2  A: 

You could double wrap it

{% block noheader %}
  <h2>{% block header %}Super Cool Page!{% endblock header %}</h2>
{% endblock noheader %}

On pages without header

{% block noheader %}{% endblock %}
czarchaic
Yeah, this is what we ended up going with. Still, it would be useful to test for the existence of a block set through descendant templates.
CommanderVoms