Login

versioned_media templatetag

Author:
dnordberg
Posted:
August 6, 2008
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

Best practice based on YSlow recommendations, add the following to your Apache config for your media directory.

<Directory /home/.../site_media/>
    ...
    FileETag None
    ExpiresActive on
    ExpiresDefault "access plus 10 years"
    AddOutputFilterByType DEFLATE text/css application/x-javascript
</Directory`

Make sure to enable mod_deflate and mod_expires.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import os
from django.conf import settings
from django import template

register = template.Library()

@register.simple_tag
def versioned_media(path):
    """Allows auto versioning of files based on modification times.
    Example: {% versioned_media "script.js" %} returns '/site_media/script.js?1217877755'
    """
    modification_time = os.path.getmtime(os.path.join(settings.MEDIA_ROOT, path))
    return "".join([settings.MEDIA_URL, path, "?%s" % int(modification_time)])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

pigletto (on August 7, 2008):

There are two issues:

  1. AFAIK using query string parameter may cause some browsers not to cache scripts

  2. there already is nice solution for this kind of stuff: django-compress

I had my own solution, similiar to yours, but when django-compress appeared I've switched to it and so far I'm very happy with this.

#

dnordberg (on August 7, 2008):

I used django_templatecomponents which provides most of the minification and grouping features django-compress does.

In regards to the query string causing some browsers not to cache scripts, can you elaborate?

For my applications I don't really need to support older browsers.

#

Please login first before commenting.