Django: How do you avoid polluting the parent context in an include tag?
Here's the code I'm trying to do:
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 context with our own variables.
new_context = copy(context)
new_context['page_url'] = url
return new_context
Unfortunately this still pollutes the template context that this include tag is calling.
<div id="content">
{% header %}
HERE THE URL: {{ page_url }}
</div>
page_url
will show up after "HERE URL:" because the parent context has been polluted.
How do I avoid this while still being able to pass the full parent context to my template with new variables?
+3
source to share
2 answers