Django block.super doesn't render variable set in parent template

576 Views Asked by At

I have the following scenario:

2 views:

view1:

return render(request, 'template1.html', {'var1': 'value1'} )

view2:

return render(request, 'template2.html', {'var2': 'value2' } )

2 templates:

template1.html

{% block foo %}
{{ var1 }}
{% endblock %}

template2.html

{% extends template1.html %}
{% block foo %}
{{ block.super }}
{{ var2 }}
{% endblock %}

Desired Output of Template1.html:

value1

Real Output of Template1.html:

value1

Desired Outputof Template2.html:

value1 value2

Real Output:

value2

Why is the value of 'var1' not output when I call {{block.super}}?

I have the 'django.core.context_processors.request', in my settings.py defined. What am I missing?

2

There are 2 best solutions below

0
On

If you don't provide var1in the context in view2 then how do you think the template will get it ? Change your settings.TEMPLATE_STRING_IF_INVALID to something else than the empty string and you'll know why var1 doesn't show up...

1
On

template2.html extends template1.html, but that does not mean view2 extends view1. You need to add var1 to the context information in view2.

# view2
return render(request, 'template2.html', {
    'var1': 'value1',
    'var2': 'value2'
})