Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for existence of template block in a template

Tags:

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?

like image 954
jjt Avatar asked Jan 09 '10 23:01

jjt


3 Answers

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 %}
like image 76
czarchaic Avatar answered Oct 13 '22 21:10

czarchaic


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.

like image 37
gruszczy Avatar answered Oct 13 '22 23:10

gruszczy


Afaik there is no really good and simple solution yet. Besides the option offered by czarchaic you could also write your own template tag as described in Jarret Hardie's answer to "How to test for use of a django template block?". However, imho the best and most elegant way will be the {% capture as ... %} template tag - unfortunately it is not implemented yet: https://code.djangoproject.com/ticket/6378

like image 21
Gerald Senarclens de Grancy Avatar answered Oct 13 '22 22:10

Gerald Senarclens de Grancy