模版中的變量由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)) #httpresponse
也可以簡寫為:
- 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): #context處理器
- return {'age':22,'user':request.user}
- #view 代碼塊
- 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',#django1.4 or after
- 'django.core.context_processors.auth', #django1.4 before
- '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",並把其返回值渲染到模版中。
參考: