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


I think you want something like this:

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

      



Hope it helps

+3


source


Before updating the existing context push()

to the stack. After rendering your template with the changed context pop()

to restore the previous values.



This is documented here .

0


source







All Articles