这是我正在尝试运行的代码:
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 THE URL:”之后呈现,因为父上下文已被污染。
如何避免这种情况,同时仍然能够使用新变量将完整的父上下文传递到我的模板中?
最佳答案
我认为你需要这样的东西:
new_context = {'page_url': url}
new_context.update(context)
return new_context
希望这有帮助
关于Django:如何避免污染包含标签中的父上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27849019/