function inject_template_vars
A Flask context processor that injects the get_file_version function into all Jinja2 templates, making it globally available for cache-busting static files.
/tf/active/vicechatdev/vice_ai/new_app.py
106 - 110
simple
Purpose
This function serves as a Flask context processor decorator that automatically makes the get_file_version function available to all templates in the application. This is typically used for cache-busting by appending version numbers or timestamps to static file URLs, ensuring browsers load the latest versions of CSS, JavaScript, and other static assets after deployments.
Source Code
def inject_template_vars():
"""Inject template variables for all templates"""
return {
'get_file_version': get_file_version,
}
Return Value
Returns a dictionary containing template variables to be injected into all templates. The dictionary has one key 'get_file_version' mapped to the get_file_version function object, making it callable within Jinja2 templates.
Dependencies
flask
Required Imports
from flask import Flask
Usage Example
from flask import Flask
app = Flask(__name__)
def get_file_version(filepath):
"""Return version string for cache busting"""
import os
import time
try:
mtime = os.path.getmtime(os.path.join(app.static_folder, filepath))
return str(int(mtime))
except:
return str(int(time.time()))
@app.context_processor
def inject_template_vars():
"""Inject template variables for all templates"""
return {
'get_file_version': get_file_version,
}
# In your Jinja2 template:
# <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}?v={{ get_file_version('css/style.css') }}">
Best Practices
- Ensure get_file_version function is defined before registering this context processor
- Keep the dictionary returned by context processors lightweight to avoid performance overhead on every template render
- Use context processors only for truly global template variables that are needed across multiple templates
- The get_file_version function should handle exceptions gracefully to prevent template rendering failures
- Consider caching file version results if the get_file_version function performs expensive operations like file system checks
- This decorator must be applied to the Flask app instance before the first request is handled
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function inject_cache_buster 79.7% similar
-
function get_file_version_v1 65.1% similar
-
function get_file_version 64.9% similar
-
function debug_cache_info 52.6% similar
-
function get_statistical_interpretation_templates 51.5% similar