Search code examples
pythonflaskjinja2

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?


Solution

  • 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

    Flask Docs Update Feb - 2024 V2.3.x https://flask.palletsprojects.com/en/2.3.x/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