我正在寻找如何在 Django 模板中“隐藏”上下文变量的解决方案。
让我们在模板之一中具有以下结构:
{% 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 %}
我希望从示例中可以明显看出我需要实现的目标。在模板中具有类似于它在 Python 中的工作方式的本地范围。还是我从错误的角度看待它?让通用模板依赖上下文变量而不是在参数中传递值?
谢谢。
更新: 手动存储上下文变量有一些有点骇人听闻的解决方案:
{# 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 #}
没有更清洁的解决方案?如果我需要存储更多变量或整个上下文怎么办?