How do I access session data in Jinja2 templates (Bottle framework on app engine)?

和自甴很熟 提交于 2020-01-12 05:32:07

问题


I'm running the micro framework Bottle on Google App Engine. I'm using Jinja2 for my templates. And I'm using Beaker to handle the sessions. I'm still a pretty big Python newbie and am pretty stoked I got this far :) My question is how do I access the session data within the templates? I can get the session data no problem within the actual python code. And I could pass the session data each time I call a jinja template. But since I need the session data in the main menu bar of the site... that means I would have to pass it on every single page. Does anyone know if I can access it directly in the templates?

For example I need the session data for my header links:

Home | FAQ | Login

or

Home | FAQ | Logout

Any help is greatly appreciated! :D


回答1:


You can add things to the Jinja2 environment globals if you want them to be accessible to all templates. See this page for additional information.

Update:

A simple example is, for your setup code:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))

Then, in your request handling code:

env.globals['session'] = session # Your session
# Your template can contain things like {{ session['key'] }}
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')
#return response using rendered data


来源:https://stackoverflow.com/questions/2554174/how-do-i-access-session-data-in-jinja2-templates-bottle-framework-on-app-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!