Django template's context variables scope?
Question: I'm looking for a solution how to "shadow" context variables in a Django's
template.

Let's have the following structure in one of templates:

    
    
    {% block content %}
      {# set context variables with a custom tag #}
      {% paginator_ctx products %}  {# sets `paginator' in context dict #}
      {% for product in paginator.object_list %}
        {# Render elements from _outer_ loop #}
        {% paginator_ctx child_products %} {# !! replaces context !! #}
        {% for cat in paginator.object_list %}
          {# Render elements from _inner_ loop #}
        {% endfor %}
        {% include "paginator.html" %}
      {% endfor %}
      {# ?? how to restore the original context ?? #}
      {% include "paginator.html" %}  {# renders prev, next & current page number #}
    {% endblock %}
    

I hope it's obvious from the example what I'd need to achieve. To have local
scope in a template similar how it does work in Python. Or am I taking it from
a wrong side ? To have generic templates relying on context variables instead
of passing values in arguments ?

Thanks.

**Update:** There is some a bit hackish solution to manually store context
variables:

    
    
    {# outer block #}
      {% with context_var as context_var_saved %}
        {# inner/nested block overwriting context_var #}
        {% with context_var_saved as context_var %}
          {# process restored context_var #}
        {% endwith %}
        {# end of inner block #}
      {% endwith %}
    {# end of outer block #}
    

No cleaner solution available ? What if I'd need to store more variables or
the whole context ?


Answer: 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.

