"""
Django template tags to enable the use of the modconcat Apache module. Set ENABLE_CONCAT=True in settings.py to enable.
http://code.google.com/p/modconcat
"""
import re
HREF_PATTERN = re.compile('href="([^"]*)"')
SRC_PATTERN = re.compile('src="([^"]*)"')
from django import template
from django.template import Template
register = template.Library()
from django.conf import settings
def _concat_enabled():
""" Tests if concatenation is enabled in the settings file. """
return hasattr(settings, 'ENABLE_CONCAT') and settings.ENABLE_CONCAT
@register.tag
def cssconcat(parser, token):
"""
Takes a block of one or more elements, concatenates all of the href's together
into a single href suitable for modconcat. Example:
...becomes...
"""
tag_name, basepath = token.split_contents()
nodelist = parser.parse(('endcssconcat',))
parser.delete_first_token()
return ConcatCssNode(nodelist, basepath[1:-1]) #strip quotes
@register.tag
def jsconcat(parser, token):
"""
Takes a block of one or more
...becomes...
"""
tag_name, basepath = token.split_contents()
nodelist = parser.parse(('endjsconcat',))
parser.delete_first_token()
return ConcatJavascriptNode(nodelist, basepath[1:-1]) #strip quotes
class ConcatCssNode(template.Node):
""" Renders the cssconcat template tag """
def __init__(self, nodelist, basepath):
self.nodelist = nodelist
self.basepath = basepath
def render(self, context):
""" Renders the cssconcat template tag """
if _concat_enabled():
output = self.nodelist.render(context)
basepath = Template(self.basepath).render(context)
css_paths = HREF_PATTERN.findall(output)
return u'' % \
(basepath, ','.join(css_paths).replace(basepath, ''))
return self.nodelist.render(context)
class ConcatJavascriptNode(template.Node):
""" Renders the jsconcat template tag """
def __init__(self, nodelist, basepath):
self.nodelist = nodelist
self.basepath = basepath
def render(self, context):
""" Renders the jsconcat template tag """
if _concat_enabled():
output = self.nodelist.render(context)
basepath = Template(self.basepath).render(context)
javascript_paths = SRC_PATTERN.findall(output)
return u' ' % \
(basepath, ','.join(javascript_paths).replace(basepath, ''))
return self.nodelist.render(context)