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

核能气质少年 提交于 2019-12-20 20:15:44

问题


Say 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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7017990/get-variables-from-a-settings-py-file-in-a-jinja-template-with-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!