Context Processors
A context processor adds variables to the template context for every render.
Useful for:
- site name
- current year
- navigation links
- feature flags
flowchart TD A["a request arrives"] --> B["push application context"] B --> C["push request context"] C --> D["your view runs"] D --> E["pop request context"] E --> F["pop application context"] B -.-> G["current_app, g available"] C -.-> H["request, session available"] I["a CLI command or a background job"] --> J["with app.app_context():"] J --> G J -.->|"still NOT available"| H
Example
Section titled “Example”import datetime
@app.context_processor
def inject_globals():
return {
"site_name": "PythonCentralHub",
"year": datetime.datetime.now().year,
}Now every template can use:
<footer>
<p>© {{ year }} {{ site_name }}</p>
</footer>Best practice
Section titled “Best practice”Keep context processors small.
Don’t put heavy database queries in them.
If you need navigation loaded from DB, consider caching.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading