Django:你如何避免污染包含标签中的父上下文?

时间:2015-01-08 20:32:50

标签: django django-templates

这是我正在尝试的代码:

from django import template
from copy import copy
register = template.Library()

# Renders the site header.
@register.inclusion_tag('site/tags/header.tpl', takes_context=True)
def header(context):
    # Load up the URL to a certain page.
    url = Page.objects.get(slug='certain-page').url

    # Pass the entire context from our parent into our own template, without polluting
    # our parent's context with our own variables.
    new_context = copy(context)
    new_context['page_url'] = url
    return new_context

不幸的是,这仍然会污染调用此包含标记的模板的上下文。

<div id="content">
  {% header %}
  HERE'S THE URL: {{ page_url }}
</div>

page_url仍将在“HERE'S URL:”之后呈现,因为父上下文已被污染。

我如何避免这种情况,同时仍然可以使用新变量将完整的父上下文传递到我的模板中?

2 个答案:

答案 0 :(得分:3)

我认为你需要这样的东西:

new_context = {'page_url': url}
new_context.update(context)
return new_context

希望这有帮助

答案 1 :(得分:0)

在更新现有上下文之前,push()将其添加到堆栈中。使用修改后的上下文渲染模板后,pop()将其还原以前的值。

记录在案here

相关问题