This Template Tag computes the font-size of two given arguments and returns a CSS-encoded string like "font-size: XXpx;", which can be used to format the font-size of link. (The minium font-size must be set with CSS.)
Requires two arguments: 1. occurrence of the current tag 2. sum of all occurrences
It works great for my tag-cloud.
Source of the logarithmic formula
Usage
<a href="http://www.anything.com" {% cloudify variable.occurrence overall. occurrence_sum %} title="anything">any tag</a>
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 | 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)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.