模版中的变量由context中的值来替换,若是在多个页面模版中含有相同的变量,好比:每一个页面都须要{{user}},笨办法就是在每一个页面的请求视图中都把user放到context中。
- from django.temlate import loader,Context
-
- t = loader.get_template('xx.html')
- c = Context({'user':'zhangsan'})
- return HttpResponse(t.render(c))
也能够简写为:
- from django.short_cuts import render_to_response
- render_to_response('xxx.html',{'user':'zhangsan'})
但 是这样写很差的地方是就是形成代码的冗余,不易维护,此时就能够用Context的一个子 类:django.template.RequestContext,在渲染模版的时候就不须要Context,转而使用RequestContext。 RequestConntext须要接受request和processors参数,processors是
context处理器的列表集合。
context处理器
- from django.template import RquestContext
- def custom_pros(request):
- return {'age':22,'user':request.user}
- c = RequestContext(request,{'name':'zhang'},processors=[custom_pros])
- return HttpResponse(t.render(c))
这 样在每一个试图中只需把custom_pros传递给RequestContext的参数processors就好了。若是是 render_to_response与RequestContext结合使用,那么render_to_response接收参数 context_instance.
- render_to_response('xxx.html',{'name':'zhang'},context_instance=RequestContext(request,processors[custom_pros])
可是这样仍是很麻烦,代码的冗余并无真正解决,你不得不在试图函数中明确指定context处理器,为此,Django提供了全局的context处理器。
全局context处理器
默认状况下,Django采用参数
TEMPLATE_CONTEXT_PROCESSORS指定默认处理器,意味着只要是调用的RequestContext,那么默认处理器中返回的对象都就将存储在context中。
template_context_processors 默认在settings文件中是没有的,而是设置在global_settings.py文件中,若是想加上本身的context处理器,就必须在本身的 settings.py中显示的指出参数:TEMPLATE_CONTEXT_PROCESSORS
默认:
- TEMPLATE_CONTEXT_PROCESSORS = (
- 'django.contrib.auth.context_processors.auth',
- 'django.core.context_processors.auth',
- 'django.core.context_processors.debug',
- 'django.core.context_processors.i18n',
- 'django.core.context_processors.media',
- 'myapp.processor.foos',
- )
或者是:
- from django.conf import global_settings
- TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS +("myapp.processor.foos",)
此时,在试图中只要把request参数传递给RquestContext就ok了。
- render_to_response('xxx.html',{'age':33},context_instance=RequestContext(request))
系统在接受到该视图的请求时,自动执行处理器 “myapp.processor.foos",并把其返回值渲染到模版中。
参考: