6👍
✅
You can solve this by extending your currently-included templates, then including the extension instead of the the currently-included base template.
37👍
It seems to be little known that you can use the with
keyword with the include
to pass variables into the context of an included template – you can use it to specify includes in the included template:
# base.html
<html>
<body>
{% block header %}{% include "header.html" %}{% endblock %}
</body>
</html>
# header.html
# some stuff here
<div id="header">
<img src="logo.png">
{% include nav_tmpl|default:"navigation.html" %}
</div>
# special_page.html (uses other navigation)
{% extends "base.html" %}
{% block header %}
{% include "header.html" with nav_tmpl="special_nav.html" %}
# you might also want to wrap the include in an 'if' tag if you don't want anything
# included here per default
{% endblock %}
This approach saves you at least from having one additional file just for the purpose of overwriting a block. You can also use the with
keyword to pass a value through a bigger hierarchy of includes as well.
- [Django]-What's the best way to handle Django's objects.get?
- [Django]-Is virtualenv recommended for django production server?
- [Django]-Is it OK to use multiple inheritance with Django abstract models?
16👍
A terser variant to the solution proposed by @Bernhard Vallant:
# base.html
<html>
<body>
{% block header %}{% include "header.html" %}{% endblock %}
</body>
</html>
# header.html
# some stuff here
<div id="header">
<img src="logo.png">
{% include nav_tmpl|default:"navigation.html" %}
</div>
# special_page.html (uses other navigation)
{% extends "base.html" %}
{% block header %}
{% with nav_tmpl="special_nav.html" %}
{{ block.super }}
{% endwith %}
{% endblock %}
- [Django]-Django datefield filter by weekday/weekend
- [Django]-How to query Case-insensitive data in Django ORM?
- [Django]-Django FileField with upload_to determined at runtime
Source:stackexchange.com