Context Processors
A context processor adds variables to the template context for every render.
Useful for:
- site name
- current year
- navigation links
- feature flags
Example
python
import datetime
@app.context_processor
def inject_globals():
return {
"site_name": "PythonCentralHub",
"year": datetime.datetime.now().year,
}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>© {{ year }} {{ site_name }}</p>
</footer>html
<footer>
<p>© {{ year }} {{ site_name }}</p>
</footer>Best practice
Keep context processors small.
Don’t put heavy database queries in them.
If you need navigation loaded from DB, consider caching.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
