# -*- coding: utf-8 -*- import string from django import template from django.conf import settings from django.template import resolve_variable register = template.Library() class MenuNode(template.Node): def __init__(self, file_path, params): self.file_path = file_path self.params = params def render(self, context): self.file_path = resolve_variable(self.file_path, context) if not self.file_path.startswith('/'): self.file_path = settings.MEDIA_URL+self.file_path file_type = self.file_path.split('.')[-1:][0].lower() params = {'file_path': self.file_path} if file_type == 'css': tpl = string.Template('') try: params['optimal'] = self.params[:1][0] or u'screen' except IndexError: params['optimal'] = u'screen' elif file_type == 'js': tpl = string.Template('') elif file_type in ['png', 'jpg', 'jpeg', 'gif']: tpl = string.Template('$alt') try: params['alt'] = self.params[:1][0] except IndexError: template.TemplateSyntaxError, 'static tag using for images require ALT text parameter' try: #params['optional'] = self.params[1:][0] dim = self.params[1:][0].split('x') params['optional'] = 'width="%s" height="%s"' % (dim[0], dim[1]) except IndexError: params['optional'] = u'' return tpl.substitute(**params) @register.tag def static(parser, token): """ {% static file_name_from_context [media] %} -> {% static "css/styles.css" [media] %} -> {% static "/css/styles.css" [media] %} -> {% static "js/script.js" %} -> {% static "img/image.(png|jpg|jpeg|gif)" "alt" [[H]x[W]] %} -> alt """ bits = token.split_contents() tag = bits.pop(0) try: file_path = bits.pop(0) except IndexError: raise template.TemplateSyntaxError, "%r tag requires at least one param" % tag return MenuNode(file_path, bits)