1

我有一个带有上下文的模板标签。在其中,我将一个变量添加到我的上下文中。似乎这个变量在包含我的模板标签的模板中正确打印(我们称之为“桌面”)。但是在包含 THAT 模板的模板中,它不再具有变量。

我用谷歌搜索了 django 文档,因为我很好奇这里发生了什么。我的模板标签的上下文变量是否仅在包含它的模板中可用,而不是看起来那样?

4

1 回答 1

2

在 Django 库中,django.template.base 中有parse_bits函数。在这个函数中,视图上下文被复制到一个新变量中。

if takes_context:
    if params[0] == 'context':
        params = params[1:]
    else:
        raise TemplateSyntaxError(
            "'%s' is decorated with takes_context=True so it must "
            "have a first argument of 'context'" % name)

并且在 class InclusionNode类的渲染函数中,创建了一个新的上下文对象来渲染模板标签的模板:

class InclusionNode(TagHelperNode):

            def render(self, context):
                """
                Renders the specified template and context. Caches the
                template object in render_context to avoid reparsing and
                loading when used in a for loop.
                """
                resolved_args, resolved_kwargs = self.get_resolved_arguments(context)
                _dict = func(*resolved_args, **resolved_kwargs)

                t = context.render_context.get(self)
                if t is None:
                    if isinstance(file_name, Template):
                        t = file_name
                    elif isinstance(getattr(file_name, 'template', None), Template):
                        t = file_name.template
                    elif not isinstance(file_name, six.string_types) and is_iterable(file_name):
                        t = context.template.engine.select_template(file_name)
                    else:
                        t = context.template.engine.get_template(file_name)
                    context.render_context[self] = t
                new_context = context.new(_dict)
                # Copy across the CSRF token, if present, because
                # inclusion tags are often used for forms, and we need
                # instructions for using CSRF protection to be as simple
                # as possible.
                csrf_token = context.get('csrf_token', None)
                if csrf_token is not None:
                    new_context['csrf_token'] = csrf_token
                return t.render(new_context)

所以它不应该将模板标签上下文传播到调用模板。

于 2015-12-04T13:40:48.150 回答