This is the same as {% widthratio %} but when the given value is greater than the max_value it just uses the max_value. This way the result is never greater than max_value. It also returns max_width if the max_value is 0 instead of returning a blank string. Usage example: {% smart_widthratio this_value max_value 100 %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.