Django RequestContext用法


模版中的變量由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",並把其返回值渲染到模版中。
參考:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM