【问题标题】:Pass context through multiple nested inclusion tags in Django通过 Django 中的多个嵌套包含标签传递上下文
【发布时间】:2017-05-03 21:57:10
【问题描述】:

我想通过 Django 中的多个包含标签传递“上下文”变量,如下所示:

base.html:

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

目录.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'

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

【问题讨论】:

    标签: django templatetags inclusion


    【解决方案1】:

    您正在使用 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'),
            # ...
        }
    

    【讨论】:

    • 这就像一个魅力。非常感谢您的帮助!
    • 派对迟到了,但你拯救了我的一天!谢谢。
    猜你喜欢
    • 2011-04-21
    • 2023-04-07
    • 2011-11-29
    • 2020-10-26
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多