[Fixed]-Is there a way to make a block optional in Django template

9👍

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 %}

29👍

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

0👍

I would only have to add to the good answers above that depending on the Django version sometimes the {{ block.super }} puts the content from the master twice, this seems to happen in the most recent versions of Django.

I am using Django 1.8 and whenever i put the {{ block.super }} it started to behave in that way just as an addition to the Jamie answer i can say that in the base template you can put the content you wish

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

And then in the child if you want the footer to be inherited and displayed just do not do anything it will be. But if you do not want that block to be displayed then put the tag in the child with empty content just like this:

{% block title %}

{% endblock %}

Then it will be hidden once it is rendered also you can overwrite the content on it if you wish.

Leave a comment