python - Django 查看模板的默认值

标签 python django templates view

有什么方法可以将变量传递给所有模板吗?例如我有一个 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)

关于python - Django 查看模板的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545952/

相关文章:

python - Django channel ; ECHO 示例不起作用

c# - 修改 Entity Framework 类型 T4 模板

c++ - SFINAE 因枚举模板参数而失败

python - 如果文件在 Python 中不存在,则以原子方式创建文件

python - 我如何加速 python 嵌套循环?

python - 在Python中解析独占组

python - Pandas 选择并写入包含特定文本的行

django - 错误 : Field cannot be both deferred and traversed using select_related at the same time? 的可能原因

python - 将父子模型对象保存在一起

javascript - emberjs 中的嵌套路由而不使用资源导出