django template context_processors 模板全局变量

本文介绍如何在Django中使用Context Processors为所有模板提供通用上下文变量,例如用户的用户名和角色等,简化视图函数的编写,并提高代码复用率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每次返回response,都要加一样的变量,如,{'user': username, 'role': role}。

这时候采用 context_processors 可以在每次返回时不用带{'user': username, 'role': role},而是将这些变量写到 context_processors 里面。


iaasms/settings.py

老版本的 Django
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'iaasms/render/templates'),
)
TEMPLATE_CONTEXT_PROCESSORS= (
    'django.contrib.auth.context_processors.auth',
    # 'django.core.context_processors.debug',
    # 'django.contrib.messages.context_processors.messages',
    'iaasms.context_processors.template_variable', # 自定义
)
新版本的 Django

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "iaasms/render/templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'iaasms.context_processors.template_variable'
            ],
        },
    },
]

iaasms/context_processors.py

def template_variable(request):
    context = {'user': username, 'role': role}
    return context

views.py

from django.shortcuts import render, render_to_response, RequestContext
def log(request):
    return render(request, 'log.html', {'a': 'a', 'b': 'b'})
    return render_to_response('log.html', {'a': 'a', 'b': 'b'}, context_instance=RequestContext(request))
以上两种返回都经过 context_processors,即加上渲染模版的变量 {'user': username, 'role': role}
下面这种不经过 context_processors:
    return render_to_response('log.html', {'a': 'a', 'b': 'b'})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值