views:

57

answers:

2

In Django's templates system, if I have a block that I want to make optional using an if statement, how do I do it?

I was trying this:

{% if val %}{% block title %}Archive {{ foo }}{% endblock %}{% endif %}

But that doesn't work. Is there a way to do that, so that for a given value (in this case Null) the block isn't issued and the base template uses the original values?

Edit: Let me be a little more specific, so that it is easier to answer.

I have a page with 10 entries per page. The user can then go on to the next page and see the next ten items. For each further page they go, past the first, I would like to have the title tag say something like "Archive 1" or "Archive 10" but if they get back to the original page, it is no longer archive, and it should just go to the original site title already given in the base templates.

+1  A: 

As far as I understand blocks are placeholders to be "overridden" in the child templates. They have to be defined at "compile time" and not at "run time".

As for your specific problem why not modify the title based on the page number (assuming you use pagination)? Something like this:

{% block title %}
    {% ifequal page 1 %}Current{% else %}Archive {{ page }}{% endifequal %}
{% endblock %}
Manoj Govindan
Yes, that is what I have now done, thanks.
Vernon
+2  A: 

I ran into a similar issue with a project I'm working on. Here's how I resolved it using {{ block.super }} to pull the default value from the parent block:

My parent template contains:

{% block title %}Default Title{% endblock %}

My child template contains:

{% block title %}
    {% if new_title %}{{ new_title }}{% else %}{{ block.super }}{% endif %}
{% endblock %}

*Note: You may want to wrap the code in {% spaceless %}{% endspaceless %} if you plan to use the result in an HTML title tag.

(It looks like Jordan Reiter posted the same solution in the comments of the original question a bit before my response.)

Jamie
Thanks, I knew from the beginning that I could just put if statements inside the block, I had just wondered, I guess, if I would make a block optional - I guess not.
Vernon