Skip to main content
 首页 » 编程设计

python之Django 查看模板的默认值

2025年05月04日36jpfss

有什么方法可以将变量传递给所有模板吗?例如我有一个 View 包含

render_to_response('page.html', dictionary, \ 
context_instance = RequestContext(request)) 

我想将另一个不在字典中的变量传递给模板文件。

目的是什么?假设我在所有 View (几百个)中都需要这个变量,而且我很想在不触及字典的情况下将这个变量传递给模板文件。顺便说一句,这个变量是一个函数的结果,它有一个参数(请求)。

可行吗?

请您参考如下方法:

您需要编写自定义 context processor .

A context processor has a very simple interface: It’s just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

Custom context processors can live anywhere in your code base. All Django cares about is that your custom context processors are pointed-to by your TEMPLATE_CONTEXT_PROCESSORS setting.

例如:

# in project/context_processors.py 
def add_extra_variable(request): 
    return {'extra': myfunction(request)} 
 
# in settings.py: 
TEMPLATE_CONTEXT_PROCESSORS = ( 
    "django.contrib.auth.context_processors.auth", 
    "django.core.context_processors.debug", 
    "django.core.context_processors.i18n", 
    "django.core.context_processors.media", 
    "django.core.context_processors.static", 
    "django.core.context_processors.tz", 
    "django.contrib.messages.context_processors.messages", 
    "project.context_processors.add_extra_variable" 
 ) 

P.S.:如果您使用 render 而不是 render_to_response,则不需要传递 RequestContext。

render('page.html', dictionary)