现在的位置: 首页 > 综合 > 正文

Django的TEMPLATE_CONTEXT_PROCESSORS使用

2013年10月22日 ⁄ 综合 ⁄ 共 977字 ⁄ 字号 评论关闭

Django提供对全局 context处理器的支持。TEMPLATE_CONTEXT_PROCESSORS指定了总是使用哪些contextprocessors。这样就省去了每次使用RequestContext都指定processors的麻烦^_^

1.打开settings.py文件,也许里面没有TEMPLATE_CONTEXT_PROCESSORS,那就自己添加一个。设置如下:
 

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
)
 这些函数都接受一个request对象作为参数,返回了一个字典。
 
1. django.core.context_processors.auth
如果TEMPLATE_CONTEXT_PROCESSORS包含了这个处理器,那么每个RequestContext将包含这些变量:
user:描述了当前登录用户
messages:一个当前登录用户的消息列表
perms:包含了当前登录用户有哪些权限
2.django.core.context_processors.debug
把调试信息发送到模板层
3.django.core.context_processors.i18n
国际化的信息
4.django.core.context_processors.request
每个处理器将包含变量request对象。
 
然后,在view中如下:
from django.template import RequestContext
c=RequestContext(request)
return render_to_response('template/register.html',c)
最后,在template中如下使用:
{{STATIC_URL}}
<img src="{% static "image/hi.jpg" %}" />
 
ok!了
【上篇】
【下篇】

抱歉!评论已关闭.