【问题标题】:Jinja2 and Flask: Pass variable into parent template without passing it into childrenJinja2 和 Flask:将变量传递给父模板而不将其传递给子模板
【发布时间】:2013-07-23 19:19:11
【问题描述】:

假设我有一个带有标题的基本模板,并且该标题的内容需要传递到模板中。

<header>
  You are logged in as {{ name }}
</header>

这个基本模板被许多页面扩展。如何在不将其传递给每个孩子的情况下传递该变量?例如,我不想这样做:

render_template("child1.html", name=user.name)
render_template("child2.html", name=user.name)
render_template("child3.html", name=user.name)
etc...

因为谁知道我可能有多少子页面。感觉不够干。

我从未真正渲染基本模板,只渲染它的子模板,但我不知道如何传递数据。

有没有办法做到这一点?我不应该使用继承吗?

【问题讨论】:

    标签: python templates variables flask jinja2


    【解决方案1】:

    我建议你在flask 中使用全局变量'g'。这在 jinja 模板中默认可用。因此,您无需担心在基本模板或子模板中的任何位置传递它。只需确保您在登录时先设置它

    g.username = user.name
    

    然后在模板中,这样做:

    You are logged in as {{ g.username }}
    

    【讨论】:

    • 最新的 Flask 版本(我相信从 0.10 开始)给出了这个错误:RuntimeError: working outside of application context。谁知道怎么处理?
    【解决方案2】:

    你需要使用Flask的context-processors:

    @app.context_processor
    def inject_user():
        return dict(user=g.user)
    

    看到这个类似的SO question and answer

    我如何使用它的一个例子(简单地插入应用程序配置设置):

    @app.context_processor
    def lib_versions():
        return dict(
            bokehversion = app.config['BOKEH_VERSION'],
            jqueryversion = app.config['JQUERY_VERSION'],
            jqueryuiversion = app.config['JQUERYUI_VERSION'],
            bootstrapversion = app.config['BOOTSTRAP_VERSION'],
        )
    

    从我的 Flask 配置文件中提取:

    class Config(object):
        DEBUG = True
        TESTING = True
        SQLALCHEMY_DATABASE_URI = ''
        TMP_DIR = ''
        STATIC_FOLDER = ''
        BOKEH_VERSION = '0.8.2'
        JQUERY_VERSION = '1.11.2'
        JQUERYUI_VERSION = '1.11.4'
        BOOTSTRAP_VERSION = '3.3.4'
    
    class ProductionConfig(Config):
        DEBUG = False
        TESTING = False
    

    然后您可以像任何其他 Jinja2 变量一样在基本模板中调用它们:

    <!-- START: CSS -->
    <link rel="stylesheet" media="screen" type="text/css" href="http://cdn.bokeh.org/bokeh/release/bokeh-{{ bokehversion }}.min.css">
    <!-- END: CSS -->
    <!-- START: JS -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/{{ jqueryversion }}/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/{{ jqueryuiversion }}/jquery-ui.min.js"></script>
    <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/{{ bootstrapversion }}/js/bootstrap.min.js"></script>
    <!-- END: JS -->
    

    【讨论】:

      猜你喜欢
      • 2015-10-23
      • 1970-01-01
      • 2011-03-13
      • 2023-01-11
      • 2011-12-26
      • 2017-11-10
      相关资源
      最近更新 更多