假设我有一个包含一堆常量的settings.py文件(将来可能会有更多)。如何在Jinja模板中访问这些变量?
Flask会自动在标准上下文中包含应用程序的配置。因此,如果您使用app.config.from_envvar
或app.config.from_pyfile
从您的设置文件中拉入值,您已经可以访问这些值在您的Jinja模板(例如,{{ config.someconst }}
)。
您需要定义一个context_processor
:
@app.context_processor
def inject_globals():
return dict(
const1 = const1,
const2 = const2,
)
以这种方式注入的值将直接在模板中可用:
<p>The values of const1 is {{ const1 }}.</p>
您可能希望使用Python dir
函数来避免列出所有常量。