Flask 模板中的全局变量 [英] Global variables in Flask templates

查看:38
本文介绍了Flask 模板中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能不是准确的标题,因为我是 Flask/python 的新手.我正在开发一个将由不同团队使用的内部工具.每个团队都有不同的部署阶段,例如 alphabeta|testprod,他们也有多个区域,例如 NA, EU, AP 等...

Probably not the accurate title since i am new to flask/python. I am working on an internal tool which will be used by different teams. Each team has different stages of their deployments e.g., alpha, beta|test, prod and they also have multiple regions e.g., NA, EU, AP etc ...

现在,当我使用 redirect_template 时,我将 stageregion 作为变量发送,然后在模板中使用.然而,为每个 redirect_template 做有点麻烦.有没有更好的方法来解决这个问题?

Right now i when i am using redirect_template i am sending stage and region as variable which are then used in templates. However, doing for every redirect_template is kind of cumbersome. Is there any better approach to this?

推荐答案

我假设您的 Flask 对象的名称是 app(即 app = Flask(__name__)).

I assume your Flaskobject's name is app (i.e., app = Flask(__name__)).

app 初始化后立即放置以下代码.

Place the below code right after the app is initialized.

@app.context_processor
def inject_stage_and_region():
    return dict(stage="alpha", region="NA")

在你的 Jinja 模板中,"alpha""NA" 可以被 {{ stage }}{ 引用{ region }}.

In your Jinja templates, "alpha"and "NA" can be referenced by {{ stage }} and {{ region }}.

烧瓶文档:http://flask.pocoo.org/docs/0.12/templating/#context-处理器

为了将新变量自动注入模板的上下文中,Flask 中存在上下文处理器.上下文处理器在呈现模板之前运行,并且能够将新值注入模板上下文.上下文处理器是一个返回字典的函数.该字典的键和值然后与模板上下文合并,用于应用程序中的所有模板

To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app

这篇关于Flask 模板中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆