I am using Django’s template inheritance from a base file called base.html.
All of my apps, except one, require that {% block contents %} {% endblock %} is present in that file, which is problematic.
I am trying to find away to make the inclusion {% block contents %} {% endblock %} conditional on a variable.
What I have so far tried in base.html:
{% if some_variable %}
{% block contents %} {% endblock %}
{% endif %}
But that doesn’t seem to work.
I have also tried:
{% if some_variable %}
{% with 'base_block_content.html' as path %}
{% include path %}
{% endwith %}
{% endif %}
base_block_content.html being simply:
‘’’ {% block contents %} {% endblock %} ‘’’
But that doesn’t work either.
My only other option is to write a completely separate base.html for the one app, which doesn’t quite fit in with the ‘DRY’ concept.
Can anyone suggest a way of doing this?
Can you be a little more specific about, or provide a real example of, the issue you’re facing?
If you have a base.html
that is extended by a template, that template is not required to provide data for every block in base.html
.
If that template doesn’t “fit” the pattern defined in base.html
more fundamentally, then yes, it is appropriate for it to extend - or ignore completely - your base.html
.
Hi Ken, Many thanks for looking into this.
I am trying to integrate and customise django-two-factor-auth’s app, using their templates and my own base.py.
I am not sure that it will be very helpful to repeat their templates in this posting, so here is the link to the location on GitHub Templates .
Basically, in the two_factor app login.html extends from _base_focus.html which extends from _base.html.
I have simply made their _base.html extend from my base.html.
The relevant parts of my base.html are:
{% block content %} {% endblock %}
{% block content_wrapper %}{% endblock %}`
If I remove {% block content %} {% endblock %} the two_factor app displays correctly, but it breaks templates relating to my other apps (they are wrapped with {% block content %} {% endblock %}).
I would greatly appreciate your help with this.
Many thanks again Ken.
I’m still not following what the problem is here.
You can have both in your base.html. It’s not a problem if data is not supplied from the template that extends it.
(However, in looking at the code you linked to, the _base.html isn’t designed to extend a different template. You’re probably better off either completely replacing it or using it exactly as-is.)
Understood, many thanks Ken.
Just out of interest, is it possible to have dynamic ‘block’ tags in Django templates, as per my original question?
Thanks again.
Yes, you can create a custom context processor allowing you to make data available to the base template. See the docs starting at The Django template language: for Python programmers | Django documentation | Django
Many thanks Ken, I don’t know what we would do without you!