djangotemplatetagsinclusion

Pass context through multiple nested inclusion tags in Django


I'd like to pass the 'context' variable through multiple inclusion tags in Django like so:

base.html:

{% load extras %}
{% table_of_contents course %}

table-of-contents.html:

{% load extras %}

<h1>Table of contents</h1>
{% for section in course.sections %}
    {% display_section section %}
{% endfor %}

extras.py:

@register.inclusion_tag('table-of-contents.html', takes_context=True)
def table_of_contents(context, course):

    return {
        'course': course,
    }

@register.inclusion_tag('display_section.html', takes_context=True)
def section_expanded(context, section):

    # Identify the user from the context request
    user = context['request'].user

    return {
        'section': section,
        'completed': section.has_been_completed_by(user),
        'outstanding_modules': section.get_outstanding_modules_for(user)
    }

However, when I run the code above, I get a key error because the context variable is not passed through to the second inclusion tag:

KeyError at /courses/pivottables-video-course/table-of-contents/
'request'

How can I ensure that the context variable persists when passed through to multiple nested inclusion tags?


Solution

  • You're defining new context with return {'foo': 'bar'} for your templates – and this new context doesn't contain request key. By default context['request'] is set by request context processor (https://docs.djangoproject.com/en/dev/ref/templates/api/#django-template-context-processors-request).

    If you want to pass context['request'] through multiple tags, you can do this:

    @register.inclusion_tag('table-of-contents.html', takes_context=True)
    def table_of_contents(context, course):
    
        return {
            # ...
            'request': context.get('request'),
            # ...
        }
    
    @register.inclusion_tag('display_section.html', takes_context=True)
    def section_expanded(context, section):
    
        # Identify the user from the context request
        user = context['request'].user
    
        return {
            # ...
            'request': context.get('request'),
            # ...
        }