Created
November 8, 2011 01:34
-
-
Save dlrust/1346775 to your computer and use it in GitHub Desktop.
Jinja2 extension to append modified timestamp for cachebreaking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from django.conf import settings | |
from jinja2 import nodes | |
from jinja2.exceptions import TemplateSyntaxError | |
from jinja2.ext import Extension | |
class AssetExtension(Extension): | |
'''Jinja2 extension to append modified timestamp for cachebreaking | |
Usage: {% asset 'some/path.js' %} | |
Returns: `/static/some/path.js?1320713645`''' | |
tags = set(['asset']) | |
def parse(self, parser): | |
stream = parser.stream | |
tag = stream.next() | |
if stream.current.test('string'): | |
path = parser.parse_primary() | |
else: | |
raise TemplateSyntaxError('''\ | |
"%s" requires path to asset file''' % tag.value, tag.lineno) | |
while not parser.stream.current.type == 'block_end': | |
parser.stream.next() | |
result = self.call_method('_build_url', args=[path]) | |
return nodes.Output([nodes.MarkSafe(result)]).set_lineno(tag.lineno) | |
def _build_url(self, path): | |
file_path = '%s%s' % (settings.STATIC_ROOT, path) | |
try: | |
modified_timestamp = int(os.path.getmtime(file_path)) | |
except: | |
modified_timestamp = '' | |
href = '%s%s' % (settings.STATIC_URL, path) | |
if modified_timestamp: | |
href += '?%s' % modified_timestamp | |
return href | |
asset = AssetExtension |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks so much for posting this. It saved a ton of time and it works really well!