3 from django import template
5 from django.conf import settings as django_settings
7 from compress.conf import settings
8 from compress.utils import media_root, media_url, needs_update, filter_css, filter_js, get_output_filename, get_version
10 register = template.Library()
12 def render_common(template_name, obj, filename, version):
14 filename = get_output_filename(filename, version)
16 context = obj.get('extra_context', {})
17 context['url'] = media_url(filename)
19 return template.loader.render_to_string(template_name, context)
21 def render_css(css, filename, version=None):
22 return render_common(css.get('template_name', 'compress/css.html'), css, filename, version)
24 def render_js(js, filename, version=None):
25 return render_common(js.get('template_name', 'compress/js.html'), js, filename, version)
27 class CompressedCSSNode(template.Node):
28 def __init__(self, name):
31 def render(self, context):
32 css_name = template.Variable(self.name).resolve(context)
35 css = settings.COMPRESS_CSS[css_name]
37 return '' # fail silently, do not return anything if an invalid group is specified
43 if settings.COMPRESS_AUTO:
44 u, version = needs_update(css['output_filename'], css['source_filenames'])
48 return render_css(css, css['output_filename'], version)
52 for source_file in css['source_filenames']:
53 r += render_css(css, source_file)
57 class CompressedJSNode(template.Node):
58 def __init__(self, name):
61 def render(self, context):
62 js_name = template.Variable(self.name).resolve(context)
65 js = settings.COMPRESS_JS[js_name]
67 return '' # fail silently, do not return anything if an invalid group is specified
73 if settings.COMPRESS_AUTO:
74 u, version = needs_update(js['output_filename'], js['source_filenames'])
78 return render_js(js, js['output_filename'], version)
82 for source_file in js['source_filenames']:
83 r += render_js(js, source_file)
87 def compressed_css(parser, token):
89 tag_name, name = token.split_contents()
91 raise template.TemplateSyntaxError, '%r requires exactly one argument: the name of a group in the COMPRESS_CSS setting' % token.split_contents()[0]
93 return CompressedCSSNode(name)
94 compressed_css = register.tag(compressed_css)
97 def compressed_js(parser, token):
99 tag_name, name = token.split_contents()
101 raise template.TemplateSyntaxError, '%r requires exactly one argument: the name of a group in the COMPRESS_JS setting' % token.split_contents()[0]
103 return CompressedJSNode(name)
104 compressed_js = register.tag(compressed_js)