如何将变量的集合传递给模板

编程入门 行业动态 更新时间:2024-10-24 09:29:32
本文介绍了如何将变量的集合传递给模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

  • 我已经建立了一个使用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 and g.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 a before_request handler.

更多推荐

如何将变量的集合传递给模板

本文发布于:2023-11-08 07:51:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568788.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何将   模板

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!