from django import template from django.template import Node from django.template import TemplateSyntaxError, VariableDoesNotExist register = template.Library() class SmartWidthRatioNode(Node): def __init__(self, val_expr, max_expr, max_width): self.val_expr = val_expr self.max_expr = max_expr self.max_width = max_width def render(self, context): try: value = self.val_expr.resolve(context) maxvalue = self.max_expr.resolve(context) max_width = int(self.max_width.resolve(context)) except VariableDoesNotExist: return '' except ValueError: raise TemplateSyntaxError("widthratio final argument must be an number") try: value = float(value) maxvalue = float(maxvalue) if value > maxvalue: value = maxvalue ratio = (value / maxvalue) * max_width except (ValueError, ZeroDivisionError): return str(max_width) return str(int(round(ratio))) def smart_widthratio(parser, token): bits = token.contents.split() if len(bits) != 4: raise TemplateSyntaxError("widthratio takes three arguments") tag, this_value_expr, max_value_expr, max_width = bits return SmartWidthRatioNode(parser.compile_filter(this_value_expr), parser.compile_filter(max_value_expr), parser.compile_filter(max_width)) smart_widthratio = register.tag(smart_widthratio)