通过 Django 中的多个嵌套包含标记传递上下文

Pass context through multiple nested inclusion tags in Django

我想通过 Django 中的多个包含标记传递 'context' 变量,如下所示:

base.html:

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

table-的-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)
    }

但是,当我 运行 上面的代码时,我得到一个关键错误,因为上下文变量没有传递给第二个包含标记:

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

如何确保上下文变量在传递给多个嵌套包含标记时持续存在?

您正在使用 return {'foo': 'bar'} 为您的模板定义新上下文 – 而这个新上下文不包含 request 键。默认情况下 context['request']request 上下文处理器 (https://docs.djangoproject.com/en/dev/ref/templates/api/#django-template-context-processors-request) 设置。

如果你想通过多个标签传递context['request'],你可以这样做:

@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'),
        # ...
    }