Skip to content

Context Processors

A context processor adds variables to the template context for every render.

Useful for:

  • site name
  • current year
  • navigation links
  • feature flags
diagram two contexts, not one mermaid
Flask pushes an application context and, for an actual request, a request context inside it. Which proxies work depends on which of the two is active -- current_app and g need the application context, request and session need the request context. That is why a background job can use current_app after app.app_context() but still cannot touch request.
python
import datetime
 
@app.context_processor
def inject_globals():
    return {
        "site_name": "PythonCentralHub",
        "year": datetime.datetime.now().year,
    }

Now every template can use:

html
<footer>
  <p>&copy; {{ year }} {{ site_name }}</p>
</footer>

Keep context processors small.

Don’t put heavy database queries in them.

If you need navigation loaded from DB, consider caching.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading