Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Em Ae Avatar asked Apr 11 '17 02:04

Em Ae


1 Answers

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

like image 83
Wonjung Kim Avatar answered Sep 30 '22 10:09

Wonjung Kim