2024-04-19 05:09:18 发布
网友
假设我有一个settings.py文件,其中包含一堆常量(将来可能还会有更多)。如何在Jinja模板中访问这些变量?
Flask自动将应用程序的配置包含在standard context中。因此,如果您使用app.config.from_envvar或app.config.from_pyfile从设置文件中提取值,那么您已经可以访问Jinja模板中的这些值(例如{{ config.someconst }})。
app.config.from_envvar
app.config.from_pyfile
{{ config.someconst }}
您需要定义一个context_processor:
context_processor
@app.context_processor def inject_globals(): return dict( const1 = const1, const2 = const2, )
以这种方式注入的值将在模板中直接可用:
<p>The values of const1 is {{ const1 }}.</p>
您可能希望使用Pythondir函数来避免列出所有常量。
dir
Flask自动将应用程序的配置包含在standard context中。因此,如果您使用
app.config.from_envvar
或app.config.from_pyfile
从设置文件中提取值,那么您已经可以访问Jinja模板中的这些值(例如{{ config.someconst }}
)。您需要定义一个
context_processor
:以这种方式注入的值将在模板中直接可用:
您可能希望使用Python
dir
函数来避免列出所有常量。相关问题 更多 >
编程相关推荐