from django.conf import settings
from datetime import datetime
def site_settings(request):
"""Add site-wide settings to template context."""
return {
'site_name': settings.SITE_NAME,
'current_year': datetime.now().year,
'google_analytics_id': getattr(settings, 'GOOGLE_ANALYTICS_ID', None),
}
def user_preferences(request):
"""Add user-specific preferences if authenticated."""
if request.user.is_authenticated:
return {
'dark_mode': request.user.profile.dark_mode,
'language': request.user.profile.language,
}
return {}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'core.context_processors.site_settings', # Custom
'core.context_processors.user_preferences', # Custom
],
},
},
]
Context processors add variables to every template context automatically. I create a function that takes request and returns a dict. This is perfect for site-wide settings like site name, current year, or user preferences. I add my processor to TEMPLATES['OPTIONS']['context_processors'] in settings. Unlike middleware, processors only run when rendering templates. I keep processors lightweight since they run on every template render. For expensive data, I use caching inside the processor. This reduces duplication across views that all need the same context variables.