[英]Django template's context variables scope?
我正在尋找一種解決方案,該方法如何在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 %}
我希望從示例中可以明顯看出我需要實現的目標。 在模板中具有類似本地作用域的作用。 還是我從錯誤的角度考慮? 是否讓通用模板依賴於上下文變量而不是在參數中傳遞值?
謝謝。
更新:手動存儲上下文變量有一些棘手的解決方案:
{# 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 #}
沒有更清潔的解決方案? 如果我需要存儲更多變量或整個上下文怎么辦?
遇到類似的問題,我決定在base_site.html
模板中創建一個用於包裝所有內容的global_scope
塊,並專門使用它來分配“多個塊”上下文變量。
它是這樣的:
>> base_site.html
{% block global_scope %}
<!DOCTYPE html>
<html>
...
<more blocks here>
</html>
{% endblock global_scope %}
然后在專門的模板中:
{% 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 %}
但是,使用這種方法,您必須仔細檢查您是否沒有覆蓋其他人在模板層次結構中設置的任何變量。
此外,根據變量的大小,可能會存在內存開銷,因為直到模板的最后才將變量彈出上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.