美文网首页
django template context_processo

django template context_processo

作者: nobodyXu | 来源:发表于2018-07-04 16:29 被阅读0次

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

相关文章

网友评论

      本文标题:django template context_processo

      本文链接:https://www.haomeiwen.com/subject/ffzeuftx.html