[Answered ]-Django template's context variables scope?

2👍

Having a similar issue, I decided to create a global_scope block in my base_site.html template that wraps everything and to use it exclusively to assign “multiple blocks” context variables.

It goes like this:

>> base_site.html

{% block global_scope %}
<!DOCTYPE html>
<html>
    ...
    <more blocks here>
</html>
{% endblock global_scope %}

Then in a specialized template:

{% block global_scope %}
    {# set context variables with a custom tag #}
    {{ block.super }} {# <-- important! #}
{% endblock global_scope %}

{% block content %}
    {# the context variable is available here #}
{% endblock %}

With this approach, though, you have to double check that you are not overriding any variables that someone else set in the template hierarchy.

Furthermore, depending on the size of your variable, maybe there is a memory overhead, being that the variable won’t be popped out of the context until the very end of the template.

Leave a comment