from django import template
from django.conf import settings
import os
register = template.Library()
def add_vid_to_filename(filename, vid=os.getenv('CURRENT_VERSION_ID', None)):
"""
Add current version id to passed filename in form:
filename.ext -> filename.VID.ext
"""
if not vid:
return filename
file_ext = filename.rsplit('.',1)
if len(file_ext) < 2:
return file_ext[0]+'.'+vid
return '.'.join((file_ext[0],vid, file_ext[1]))
def css(parser, token):
"""
This will use merged css files on production or original ones on development server.
Usage::
{% load cssjs %}
{% css media all.css cssfile1 [cssfile2] .. %}
If the code is working on development server, the tag will create several links
with cssfile1 [cssfile2] etc.
If the code is run on production server, the tag will use all.css and will insert
version id before file exension.
The HTML output for this will be::
"""
tokens = token.contents.split()
if len(tokens) < 4:
raise template.TemplateSyntaxError(u"'%r' tag requires at least 3 arguments." % tokens[0])
if 'Dev' in os.getenv('SERVER_SOFTWARE'):
return template.TextNode('\n'.join(['' % (tokens[1], settings.MEDIA_URL, css) for css in tokens[3:]]))
else:
return template.TextNode('' % (tokens[1], settings.MEDIA_URL, add_vid_to_filename(tokens[2])))
def js(parser, token):
"""
This will use merged js files on production or original ones on development server.
Usage::
{% load cssjs %}
{% js all.js jsfile1 [jsfile2] .. %}
If the code is working on development server, the tag will create several links
with cssfile1 [cssfile2] etc.
If the code is run on production server, the tag will use all.js and will insert
version id before file extension.
The HTML output for this will be::
"""
tokens = token.contents.split()
if len(tokens) < 3:
raise template.TemplateSyntaxError(u"'%r' tag requires at least 2 arguments." % tokens[0])
if 'Dev' in os.getenv('SERVER_SOFTWARE'):
return template.TextNode('\n'.join(['' % (settings.MEDIA_URL, css) for css in tokens[2:]]))
else:
return template.TextNode('' % (settings.MEDIA_URL, add_vid_to_filename(tokens[1])))
register.tag('css', css)
register.tag('js', js)