使用Flas从Jinja模板中的settings.py文件获取变量

2024-04-19 05:09:18 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个settings.py文件,其中包含一堆常量(将来可能还会有更多)。如何在Jinja模板中访问这些变量?


Tags: 文件py模板settingsjinja常量
2条回答

Flask自动将应用程序的配置包含在standard context中。因此,如果您使用app.config.from_envvarapp.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>

您可能希望使用Pythondir函数来避免列出所有常量。

相关问题 更多 >