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

标签 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 THE URL:”之后呈现,因为父上下文已被污染。

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

最佳答案

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

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

希望这有帮助

关于Django:如何避免污染包含标签中的父上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27849019/

相关文章:

django - 如何在渲染 StackedInline 字段时覆盖 str 方法?

python - 迁移过程中创建FK关系

Django Infinity 作为日期时间默认值

python - 反向 'update' 关键字参数 '{' id' : '' }' not found. 1 pattern(s) tried: [' update/(? P<id>[0-9]+)/\\Z']

python - 处理带有空格的 css 类名

python - 在 Django 模板中嵌入 Plotly 图表

python - Azure Web 服务和 Django 日志

python - 如何在 Django 模板中迭代字典的列表值

Django登录表单错误消息

Django查询: How to find all posts from people you follow