如何将上下文传递给模板而不在所有视图中实际指定它?
我有一些视图,它们都工作良好,并且都使用扩展一个基本模板的模板,该基本模板输出核心 HTML、页眉、页脚、导航等。幸福的家庭。
现在,我想在页面上玩会话,因为如果不从视图中实际传递用户的会话信息,就无法从模板访问用户的会话信息(纠正我的错误),我有两个选择:
将会话数据添加到我作为上下文传递到视图中的 HTML 模板的其余位(不确定这是否是一个好方法)
以某种方式从视图继承所有现有视图,该视图始终将上下文推送到正在处理的模板 - 这样我就不必担心我可能会做的任何事情想要在将来添加到我的页面 - 这可能吗?
我对 django 很陌生,可能还有其他正确的方法来做到这一点 - 非常感谢您的所有建议。
I have a few views and they all work good and all use templates that extend one base template that outputs the core HTML, the header, footer, navigation and so on. Happy family.
now, I want to play with sessions on the pages and since you can't get access to user's session information from the template without actually passing it from the view (correct me where I'm wrong) I have two options:
add session data to the rest of the bits I pass as context to HTML templates in views (not sure if this is a good way to go)
somehow inherit all existing views from a view that will be always pushing context to templates being processed - this way I don't have to worry about anything else I may want to add to my pages in the future - is this possible?
I'm very new to django and there may be other proper way of doing this - all your suggestions are much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为添加上下文处理器是实现此目的的一种非常简单的方法。
您可以自己编写或使用这个:
DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST
http ://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request
然后你的模板中就会有请求,并且可以通过以下方式进入会话request.session
如果您这样做,请确保将视图中的 RequestContext 传递给模板,如下所示:
同时修改您的 settings.py 以添加上下文处理器
I think adding in a context processor is a very easy way to do this.
You could either write your own or use this one:
DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST
http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request
Then you will have the request in your template, and could get to the session with request.session
If you do that though, make sure that you pass the RequestContext along in your views to the templates, something like this:
Also modify your settings.py to add in the context processor