38👍
✅
I suspect that block
is what you are looking for in the first place.
Form your block inside the base template like this:
{% block sidebar_wrapper %}
{% if sidebar %}
<div class="width{{sidebar_width}}">
{% block sidebar %}{% endblock %}
</div>
{% endif %}
{% endblock sidebar_wrapper%}
And on your child template:
{% extends 'layout.html' %}
{% block sidebar_wrapper %}
{% with sidebar=True sidebar_width=4 %}
{{ block.super }}
{% endwith%}
{% endblock sidebar_wrapper%}
👤xpy
13👍
What you need is an include template tag. You can include a template in another template and render that with specific context.
{% include 'layout.html' with sidebar=True sidebar_width=4 %}
Check docs here: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#include
- [Django]-Django annotation with nested filter
- [Django]-Custom Filter in Django Admin on Django 1.3 or below
- [Django]-How to use Python type hints with Django QuerySet?
3👍
You can achieve this with some technique. I’ll show the code then explain below.
# layout.html
{% block content %}
{% if show_sidebar %}
<div class="{{ sidebar_width_class }}">
{% block sidebar %}{% endblock %}
</div>
{% endif %}
{% endblock %}
# child.html
{% extends 'layout.html' %}
{% block content %}
{% with show_sidebar=True sidebar_width_class="width_4" %}
{{ block.super }}
{% endwith %}
{% endblock %}
- In
layout.html
, wrap everything inside{% block content %}
- In
child.html
,{{ block.super }}
is like python’ssuper()
, which renders everything in the parent template’s block. So if you wrap it inside{% with %}
tag, all variables that you declare there will be available inside the parent template as well.
- [Django]-Django project base template
- [Django]-Distributed task queues (Ex. Celery) vs crontab scripts
- [Django]-How to view corresponding SQL query of the Django ORM's queryset?
Source:stackexchange.com