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

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>&copy; {{ year }} {{ site_name }}</p>
</footer>
<footer>
  <p>&copy; {{ 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 coffee

Was this page helpful?

Let us know how we did