开发者

Get variables from a settings.py file in a Jinja template with Flask

开发者 https://www.devze.com 2023-03-27 10:04 出处:网络
Sa开发者_JS百科y I have settings.py file with a bunch of constants (maybe more, in the future). How do I access those variables in a Jinja template?Flask automatically includes your application\'s con

Sa开发者_JS百科y I have settings.py file with a bunch of constants (maybe more, in the future). How do I access those variables in a Jinja template?


Flask automatically includes your application's config in the standard context. So if you used app.config.from_envvar or app.config.from_pyfile to pull in the values from your settings file, you already have access to those values in your Jinja templates (e.g., {{ config.someconst }}).


You need to define a context_processor:

@app.context_processor
def inject_globals():
    return dict(
        const1 = const1,
        const2 = const2,
    )

Values injected this way will be directly available in templates:

<p>The values of const1 is {{ const1 }}.</p>

You'll probably want to use the Python dir function to avoid listing all of the constants.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号