如何访问Jinja2模板中的会话数据(应用程序引擎上的Bottle框架)? [英] How do I access session data in Jinja2 templates (Bottle framework on app engine)?
问题描述
我在Google App Engine上运行微型框架 Bottle 。我为我的模板使用 Jinja2 。我使用 Beaker 来处理会话。我仍然是一个非常大的Python新手,我很兴奋我得到了这个:)我的问题是如何访问模板内的会话数据?我可以在实际的Python代码中获得会话数据没有问题。每次我打电话给一个jinja模板时,我都可以传递会话数据。但是因为我需要网站主菜单栏中的会话数据......这意味着我必须在每一页上传递它。有人知道我是否可以直接在模板中访问它吗?
例如,我需要我的标题链接的会话数据:
首页|常见问题|登录
或
主页|常见问题|注销
任何帮助非常感谢! :D
您可以将内容添加到Jinja2 环境全局变量,如果您希望它们可以被所有模板访问。有关更多信息,请参阅此页面。
更新:
一个简单的例子就是您的设置代码:
from jinja2 import Environment,PackageLoader
env = Environment(loader = PackageLoader('yourapplication','templates'))
$ c
$ b 然后,在您的请求处理代码中:
env.globals ['session'] = session#您的会话
#您的模板可以包含{{session ['key']}}
template = env.get_template('mytemplate。 html')
print template.render(the ='variables',go ='here')
#使用渲染数据返回响应
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
解决方案 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
这篇关于如何访问Jinja2模板中的会话数据(应用程序引擎上的Bottle框架)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!