Login

Smart widthratio

Author:
zenx
Posted:
April 25, 2010
Language:
Python
Version:
1.1
Tags:
templatetag widthratio templatetags
Score:
1 (after 1 ratings)

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

  1. Smart {% if %} template tag by SmileyChris 6 years, 4 months ago
  2. Customizable newforms labels with a template tag by exogen 7 years, 2 months ago
  3. SAS70 Compliant Password Validator by czieler 7 years, 11 months ago
  4. Check Size of Object in memcached by deryck 7 years, 7 months ago
  5. Plural templatetags if quantity > 1: return single else return plural by Natim 5 years, 6 months ago

Comments

Please login first before commenting.