Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

python - Global variables in Flask templates

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Place the below code right after the app is initialized.

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

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

Flask docs: http://flask.pocoo.org/docs/0.12/templating/#context-processors

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...