當您render_to_template模板需要渲染不同物品的字典時,其中一些常用於所有頁面,例如用戶問候語或類似的東西。有沒有辦法通過某種方式讓這種字典項目傳遞到所有模板而不必在每個視圖中明確定義它們,從而讓事情變得容易一些?django將常用詞典傳遞給模板,而不必在每個視圖中明確傳遞它們?
2
A
回答
4
這是上下文處理器的用途 - 您可以定義一個字典,將其添加到每個響應的上下文中。
它們寫起來非常簡單,只需將它們添加到設置中即可。請記住確保您使用的是RequestContext,而不是用於模板的純上下文,並且每次都會自動運行。
文檔是在這裏:https://docs.djangoproject.com/en/1.3/ref/templates/api/#writing-your-own-context-processors
1
您可以使用一個上下文處理器,如this example看到。每個render_to_response
最終會看起來像:
return render_to_response("my_app/my_template.html", {'some_var': 'foo'},
context_instance=RequestContext(request))
相關問題
- 1. 將多個視圖傳遞給模板
- 2. Django。不將外鍵傳遞給模板
- 3. 在Flask模板中使用字典而不將它傳遞給render_template
- 4. 如何將TouchUpInside事件傳遞給UIButton,而不將它傳遞給父視圖?
- 5. 將request.user傳遞給Django中的模板
- 6. 將模板中的值傳遞給Django中的視圖
- 7. 如何將對象從模板傳遞給django中的視圖?
- 8. 將字典鍵傳遞給新詞典
- 9. 將python列表傳遞給django模板
- 10. 將ajax響應傳遞給django模板
- 11. 將json blob傳遞給django模板
- 12. 將變量傳遞給Django模板
- 13. django-profile將變量傳遞給模板
- 14. Jinja2和Flask:將變量傳遞給父模板而不傳遞給子模塊
- 15. 將字典傳遞給視圖Asp.net MVC
- 16. 將對象傳遞給django視圖(控制器)FROM模板
- 17. 將多個模型傳遞給視圖
- 18. Django將不正確的查詢結果傳遞給模板
- 19. 將模板傳遞給deque
- 20. Django - 將參數從模板傳遞到視圖不起作用
- 21. 如何在模板django中使用從視圖傳遞給模板的變量?
- 22. CodeIgniter將變量傳遞給模態然後傳遞給視圖
- 23. Django - 如何將字典傳遞給模板標記
- 24. 如何將字典傳遞給Django模板?
- 25. 如何ASP.NET MVC通模型視圖,而不明確地傳遞
- 26. Django Ajax將變量傳遞給視圖
- 27. Django將對象傳遞給視圖
- 28. 骨幹視圖不會呈現傳遞給它的模板
- 29. Django - 將一個視圖中的變量傳遞給模板中的url標記
- 30. 將屬性傳遞給遞歸模板?
FWIW,如果你使用'render'方法或者基於類的意見(均在Django 1.3+),在'RequestContext'位爲你隱式進行。 – 2012-02-27 18:34:20