如何将变量的集合传递给模板 [英] How to pass collection of variables to templates
问题描述
- 我已经建立了一个使用flask和SqlAlchemy的博客引擎,具有左侧和右侧的通用基础模板右侧边栏以及根据查询动态生成的
页脚区域。 -
$ b - 在每个视图中都传递了许多变量来填充所述的侧边栏和页脚。 p>我的问题是:
是否有一种方法可以将一组变量传递给烧瓶应用程序中的每个视图,而无需在
render_template()
调用中传递它们
解决方案flask.g
。
例如,您可以有
g.left_sidebars
,g.right_sidebars
和g.footer
,每个数组都包含您正在使用的变量。这些变量可能有预先呈现的HTML(可能缓存,如果可能的话,以避免每次渲染),或者他们可能是包含子模板的名称。
由于
flask.g
自动提供给模板,所有你需要做的就是在每个请求期间或者在before_request
处理程序。I've been building a blog engine with flask and SqlAlchemy and I've reached a point where I have the following:
- A generic base template which has a left & right sidebar along with footer areas that are dynamically generated based on queries.
- A number of variables that are being passed in every view to populate said sidebars and footer.
My question is:
Is there a means by which I can pass a group of variables to every view in a flask app without having to pass them in the
render_template()
call?解决方案The easiest way to make a set of variables available to a template is to add them to
flask.g
.For example, you could have
g.left_sidebars
,g.right_sidebars
andg.footer
, each an array with the variables that you are using. These variables could have pre-rendered HTML (maybe cached if possible to avoid rendering them every time), or they could be names of sub-templates to include.Since
flask.g
is made available to the templates automatically all you need to do is populate these arrays during each request or in abefore_request
handler.这篇关于如何将变量的集合传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!