Flask + Jinja: Pass Data to a Base Template/All Templates

FlaskJinja2

Flask Problem Overview


I have a method that returns data which is needed in my base template (content for a global footer).

How do either (1) pass a variable into the base template (which other templates extend) or (2) pass a variable to all templates globally without explicitly adding it in a call to render_template?

Flask Solutions


Solution 1 - Flask

From flask docs: [Flask's Context Processors][1]

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

Example from docs:

@app.context_processor
def inject_user():
    return dict(user=g.user)

Note that this example uses the g variable, which is already accessible in templates. [1]: https://flask.palletsprojects.com/en/1.1.x/templating/#context-processors

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionokobokoView Question on Stackoverflow
Solution 1 - FlaskGohn67View Answer on Stackoverflow