標籤:blog http java 使用 os io strong 檔案
模版中的變數由context中的值來替換,如果在多個頁面模版中含有相同的變數,比如:每個頁面都需要{{user}},笨辦法就是在每個頁面的請求視圖中都把user放到context中。 Python代碼
- from django.temlate import loader,Context
-
- t = loader.get_template(‘xx.html‘)
- c = Context({‘user‘:‘zhangsan‘})
- return HttpResponse(t.render(c)) #httpresponse
也可以簡寫為: Python代碼
- 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處理器 Python代碼
- from django.template import RquestContext
- def custom_pros(request): #context處理器
- return {‘age‘:22,‘user‘:request.user}
Python代碼
- #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. Python代碼
- 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代碼
- 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‘,
- )
或者是:
Python代碼
- from django.conf import global_settings
- TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS +("myapp.processor.foos",)
此時,在試圖中只要把request參數傳遞給RquestContext就ok了。
Python代碼
- render_to_response(‘xxx.html‘,{‘age‘:33},context_instance=RequestContext(request))
系統在接受到該視圖的請求時,自動執行處理器 “myapp.processor.foos",並把其傳回值渲染到模版中。
參考:http://stackoverflow.com/questions/7470179/module-django-core-context-processors-does-not-define-a-auth-callable-requeshttp://stackoverflow.com/questions/2246725/django-template-context-processorshttps://groups.google.com/forum/?fromgroups#!topic/django-users/1ntgBhfAulI