from django import template import math register = template.Library() class Cloudify(template.Node): max_font = 40 # => Max fontsize in px min_font = 10 # => Min fontsize in px def __init__(self, tag_quantity, overall_quantity): self.tag_quantity = template.Variable(tag_quantity) self.overall_quantity = template.Variable(overall_quantity) def render(self, context): try: tag_amount = int(self.tag_quantity.resolve(context)) overall_amount = int(self.overall_quantity.resolve(context)) try: return "style=\"font-size: %ipx;\"" % int((Cloudify.max_font - Cloudify.min_font) * (math.log(tag_amount)) / (math.log(overall_amount)) + Cloudify.min_font) except: # => for (math.log(0)) / (math.log(0)) or tag_amount == overall_amount return '' except: return '' @register.tag(name="cloudify") def do_cloudify(parser, token): try: tag_name, tag_quantity, overall_quantity = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires two arguments" % token.contents.split()[0] else: return Cloudify(tag_quantity, overall_quantity)