[Django]-Is there a way to pass a variable to an 'extended' template in Django?

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

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’s super(), 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.

Leave a comment