每次返回response恩闻,都要加一樣的變量,如,{'user': username, 'role': role}挺邀。
這時(shí)候采用 context_processors 可以在每次返回時(shí)不用帶{'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))
#以上兩種返回都經(jīng)過(guò) context_processors端铛,即加上渲染模版的變量 {'user': username, 'role': role}
#下面這種不經(jīng)過(guò) context_processors:
? ? return render_to_response('log.html', {'a': 'a', 'b': 'b'})