python - 在 Django 中为您的模板提供一个全局变量

标签 python django

我希望我的所有模板都可以使用一个公共(public)变量。我整个上午都在研究这个,我能找到的唯一方法就是使用这样的中间件:

class GetNameMiddleware(object):

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_template_response(self, request, response):
        response.context_data['name'] = 'dave'
        return response

并有这样的 View :

from django.template.response import TemplateResponse
from django.shortcuts import render

def home(request):
    return TemplateResponse(request, 'home.html', {})

然后我可以在模板中访问它

Hello {{ name }}

我不能再使用 render 了> 但这并不是真正的解决方案)

(Django 1.10,python 3.5.2)

最佳答案

Django 有一个标准的方法来实现它,那就是上下文处理器。本文提供了一个示例实现 https://www.webforefront.com/django/setupdjangocontextprocessors.html .

实际上,上下文处理器只是一个接受请求对象并返回包含所需数据的字典的函数。

关于python - 在 Django 中为您的模板提供一个全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40913830/

相关文章:

python - 使用 Python 解析 JSON : TypeError: list indices must be integers, 不是 str

python - 在 Pandas 中使用 DataFrame.ix 和元组索引

python - python中的后台 worker

python - Django Haystack w/Elasticsearch Dwithin投影或单位错误?

python django项目和文件夹结构(与WAMP不同)

python - Python 中 isnumeric 和 isdecimal 的区别

python - 创建一个范围内的随机整数序列,并且它们之间的距离最小

django - django 中过滤图书列表的每位作者的图书数量

django - 属性错误: 'NoneType' object has no attribute 'attname' (Django)

python - Django runserver 绑定(bind)到 0.0.0.0,如何获取哪个 IP 接受了请求?