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
import datetime
@app.context_processor
def inject_globals():
return {
"site_name": "PythonCentralHub",
"year": datetime.datetime.now().year,
}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><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
