1

我在我的 context_processor 中定义一个函数,以从我的设置中传递一个值以在模板中使用。那么什么是正确的方法,更重要的是有什么区别?

def baseurl(request):
    return {'BASE_URL': settings.BASE_URL}

或者

def baseurl(context):
    return {'BASE_URL': settings.BASE_URL}

我一直使用第一个,但遇到了第二个的几个例子

4

2 回答 2

2

django/template/context.py

class RequestContext(Context):
    """
    This subclass of template.Context automatically populates itself using
    the processors defined in TEMPLATE_CONTEXT_PROCESSORS.
    Additional processors can be specified as a list of callables
    using the "processors" keyword argument.
    """
    def __init__(self, request, dict_=None, processors=None, current_app=None,
            use_l10n=None, use_tz=None):
        Context.__init__(self, dict_, current_app=current_app,
                use_l10n=use_l10n, use_tz=use_tz)
        if processors is None:
            processors = ()
        else:
            processors = tuple(processors)
        for processor in get_standard_processors() + processors:
            self.update(processor(request))

最后两行是最重要的。这意味着没有命名参数。因此,你如何命名你的论点并不重要。

于 2013-02-08T12:57:44.710 回答
1

你可以随意调用这个论点,但request它是最常见或最清楚的。来自 Django 文档:https ://docs.djangoproject.com/en/1.4/ref/templates/api/#writing-your-own-context-processors

上下文处理器有一个非常简单的接口:它只是一个 Python 函数,它接受一个参数,一个 HttpRequest 对象,并返回一个添加到模板上下文的字典。

虽然没有什么能阻止你命名这个参数context,但它会产生误导,因为它传递了一个 HttpRequest 对象。

于 2013-02-08T12:55:31.997 回答