Most Flask templates need a few shared variables: the site name in the header, the current year in the footer, the logged-in user’s name. Instead of passing each variable by hand into every render_template() call and forever fearing you’ll forget one spot, use @app.context_processor: a function that returns a dict, and every variable in that dict is automatically available in every template. Reach for it as soon as your project has a shared layout across multiple pages.
The Problem
A familiar situation: you have a shared layout with header/footer, and every route must remember to pass site_name:
# app.py — passing shared variables by hand in every routefrom flask import Flask, render_templateapp = Flask(__name__)@app.route("/")def index(): return render_template("index.html", site_name="Linh Fish Dev")@app.route("/about")def about(): # forgot site_name -> empty header, Jinja reports no error return render_template("about.html")@app.route("/contact")def contact(): return render_template("contact.html", site_name="Linh Fish Dev") # repeated
Three pains with this approach: first, repeated code in every route; second, forget one spot and the template renders incomplete with no error telling you; third, every time you need a new shared variable (say current_user), you must edit dozens of routes.
The Solution
A context processor is a function Flask calls right before rendering every template; the dict it returns is merged into the template’s context, so any variable you declare here is usable in every .html file:
# app.py — one place, works in every templatefrom datetime import datefrom flask import Flask, render_template, sessionapp = Flask(__name__)app.secret_key = "set-in-env"@app.context_processordef inject_common(): return { "site_name": "Linh Fish Dev", "current_year": date.today().year, }@app.context_processordef inject_user(): # runs inside the request context, so session, request, g... are usable return {"current_user": session.get("username", "guest")}@app.route("/")def index(): return render_template("index.html") # nothing extra to pass
In templates, use them like ordinary variables:
<!-- templates/layout.html --><header>{{ site_name }}</header><main>{% block content %}{% endblock %}</main><footer>© {{ current_year }} {{ site_name }} — hello {{ current_user }}</footer>
Why is this better? First, a single source of truth: rename the site in one place. Second, the processor runs inside the request context, so it can read session, request, and g — things a static config variable can’t do. Third, you can register multiple processors, each owning one group of variables (seo, user, settings) instead of cramming everything into one giant function.
Apply It to Your Project
Review your render_template() calls and list variables that repeat across 3 or more routes (site_name, current_year, current_user, settings…). Move them into a context processor placed right after create_app() (or inside the factory), and keep only page-specific variables at each route. One important caveat: don’t put expensive database queries in a processor — it runs on every template, so a costly query multiplies its cost across the whole site; for values that need a query, cache them or compute once.
Related Posts
- Flask: Use the Application Factory (create_app) So Your App Is Easy to Test and Scale from Day One
- Flask: Organize Routes Neatly with Blueprints as Your Project Grows
- Flask: Manage Config per Environment (dev/staging/prod) — No More Hardcoded SECRET_KEY
Frequently Asked Questions
When does a context processor run?
Every time render_template() (or render_template_string()) is called, Flask runs all registered processors and merges the results into the template context. For JSON-only APIs that never render templates, processors don’t run, so there’s no cost at all.
How is it different from before_request and g?
before_request runs before routes to handle the request (logging, login checks); g stores data for the lifetime of one request. A context processor does exactly one job: injecting variables into templates. You can absolutely read g, session, and request inside a processor.
Can multiple context processors override each other?
Yes: if two processors return the same variable name, the one registered later wins. The safe rule is one group of variables per processor, and avoid naming collisions with variables you pass directly at the route — route variables always beat processor variables.
Do context processors slow down my app?
The mechanism itself is nearly free; the cost is in the code you write inside. Avoid heavy database queries in processors — use caching, or compute once at startup for static values like the current year.
Do blueprints get their own context processors?
Yes: @bp.context_processor applies only to templates rendered from that blueprint’s routes. Handy when a module needs its own shared variables (e.g. an admin prefix) that you don’t want leaking into the whole app.
References
- Flask docs — Context processors: https://flask.palletsprojects.com/en/stable/templating/#context-processors
- Jinja documentation — Template Designer Documentation: https://jinja.palletsprojects.com/
