Skip to content

Instantly share code, notes, and snippets.

@wowkin2
Last active September 12, 2015 15:39
Show Gist options
  • Save wowkin2/c78dba5b9def4eb8a29b to your computer and use it in GitHub Desktop.
Save wowkin2/c78dba5b9def4eb8a29b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from django import template
from django.conf import settings
register = template.Library()
# ...
# other template tags
# ...
@register.simple_tag
def static_version(path):
""" Returns absolute URL to static file with versioning.
"""
full_path = os.path.join(os.path.abspath(settings.STATICFILES_DIRS[0]), os.path.normpath(path))
try:
# Get file modification time.
mtime = os.path.getmtime(full_path)
return '%s%s?%s' % (settings.STATIC_URL, path, mtime)
except OSError:
# Returns normal url if this file was not found in filesystem.
return '%s%s' % (settings.STATIC_URL, path)
...
{% load app_tags %}
...
<link rel="icon" href="{% static_version 'img/favicon.png' %}" type="image/x-icon">
<link rel="shortcut icon" href="{% static_version 'img/favicon.png' %}" type="image/x-icon">
<link rel="stylesheet" href="{% static_version 'css/main.css' %}" type="text/css" />
<script type='text/javascript' language="javascript" src="{% static_version 'js/main.js' %}"></script>
...
INSTALLED_APPS = (
# ...
'<app_name>.app_tags',
# ...
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment