每次返回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'})