Django——如何在Django模板中注入全局变量?——part2

模版中的变量由context中的值来替换,若是在多个页面模版中含有相同的变量,好比:每一个页面都须要{{user}},笨办法就是在每一个页面的请求视图中都把user放到context中。
 
Python代码   收藏代码
  1. from django.temlate import loader,Context  
  2.   
  3. t = loader.get_template('xx.html')  
  4. c = Context({'user':'zhangsan'})  
  5. return HttpResponse(t.render(c))   #httpresponse  
 
也能够简写为:
 
Python代码   收藏代码
  1. from django.short_cuts import render_to_response  
  2. render_to_response('xxx.html',{'user':'zhangsan'})  
 
但 是这样写很差的地方是就是形成代码的冗余,不易维护,此时就能够用Context的一个子 类:django.template.RequestContext,在渲染模版的时候就不须要Context,转而使用RequestContext。 RequestConntext须要接受request和processors参数,processors是 context处理器的列表集合。
context处理器
 
Python代码   收藏代码
  1. from django.template import RquestContext  
  2. def custom_pros(request):   #context处理器  
  3.      return {'age':22,'user':request.user}  
 
Python代码   收藏代码
  1. #view 代码块  
  2. c = RequestContext(request,{'name':'zhang'},processors=[custom_pros])  
  3. return HttpResponse(t.render(c))    
 
这 样在每一个试图中只需把custom_pros传递给RequestContext的参数processors就好了。若是是 render_to_response与RequestContext结合使用,那么render_to_response接收参数 context_instance.
 
Python代码   收藏代码
  1. 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
默认:
 
Python代码   收藏代码
  1. TEMPLATE_CONTEXT_PROCESSORS = (  
  2.            'django.contrib.auth.context_processors.auth',#django1.4  or after  
  3.            'django.core.context_processors.auth',  #django1.4 before  
  4.            'django.core.context_processors.debug',   
  5.            'django.core.context_processors.i18n',   
  6.            'django.core.context_processors.media',  
  7.            'myapp.processor.foos',  
  8. )  
 
或者是:
 
Python代码   收藏代码
  1. from django.conf import global_settings  
  2. TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS +("myapp.processor.foos",)  
此时,在试图中只要把request参数传递给RquestContext就ok了。
Python代码   收藏代码
  1. render_to_response('xxx.html',{'age':33},context_instance=RequestContext(request))  
系统在接受到该视图的请求时,自动执行处理器 “myapp.processor.foos",并把其返回值渲染到模版中。
参考:
相关文章
相关标签/搜索