5

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

<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...

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

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

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

4

2 回答 2

13

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

g.username = user.name

然后在模板中,只需执行以下操作:

You are logged in as {{ g.username }}
于 2013-07-23T19:57:33.843 回答
2

您需要使用 Flask 的上下文处理器

@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-04-30T22:37:17.660 回答