Skip to content

Instantly share code, notes, and snippets.

@rrafal
Created November 12, 2014 16:03
Show Gist options
  • Save rrafal/42ab0d76c20f44c494bc to your computer and use it in GitHub Desktop.
Save rrafal/42ab0d76c20f44c494bc to your computer and use it in GitHub Desktop.
Django template tag for creating URL with version number to static file.
import os
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(name="vstatic")
def vstatic(path):
""" Return absolute URL to static file with versioning. """
url = os.path.join(settings.STATIC_URL, path)
version = settings.STATIC_VERSION
try:
if version == 'mtime':
full_path = os.path.join(settings.STATIC_ROOT, path)
version = int(os.path.getmtime(full_path))
if '?' in url:
url = '%s&v=%s' % (url, version)
else:
url = '%s?v=%s' % (url, version)
except OSError:
print full_path
pass
return url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment