Hello Visitor! Login or Sign Up

Making Tag Clouds with Turbogears

Tag Cloud? Yawn. So yesterdays news. Still, if you've never created one and you want to give it a whirl with Turbogears and SQLObject then here's some pointers.

First, thanks to this article which describes the process. I don't add much, I just give you some examples with Python, Kid and SQLObject.

I use Tag Clouds in a couple of places in AutomaticRomantic, here's a screenshot of the gifts page :

Gifts tag cloud on AutomaticRomantic site

Here the idea is pretty simple, I keep a table (SQLObject class) of gift categories and under each category a list of merchant sites that are in that category. If someone clicks on one of the merchant links I take the click and then redirect them to the merchant site (passing my affiliate code as I do so). Before I do the redirect though, I increment the number of clicks in the parent category.

So each category (Jewelery, Teddy Bears, Collectibiles) has a counter associated with it and that should determine it's size in the tag cloud. OK, some code :

class GiftCategory(SQLObject):

name = StringCol(length=100)

clicks = IntCol(default=0)

The code to serve it up :


def gifts(self,**values):

allcats = GiftCategory.select()

cats = [cat for cat in allcats]

#find out what the max and min clicks are

nums = [cat.clicks for cat in cats]

maxn = max(nums)

minn = min(nums)

diff = (maxn - minn) / 3

#Work out what category deserves which tag

l = []

for cat in cats:

if cat.clicks == minn:

klass = 'smallestTag'

elif cat.clicks == maxn:

klass = 'largestTag'

elif cat.clicks > (minn + (diff * 2)):

klass = 'largeTag'

elif cat.clicks > (minn + diff):

klass = 'mediumTag'


klass = 'smallTag'


#Randomize them so they don't always appear in the same order


return dict(cats = l)

The klass value is going to link to a css class, the keyword class is reserved in python. Here are those classes (verbatim from Pete Freitag)

.smallestTag { font-size: xx-small;}

.smallTag { font-size: small;}

.mediumTag { font-size: medium;}

.largeTag { font-size: large;}

.largestTag { font-size: xx-large;}

So now the Kid snippet to serve that lot up :

          <span py:for="id,name,klass in cats" class="$klass"><a href="#">$name</a></span>

You know, this stuff is too easy. That's why I have a bit more styling on my tagcloud and I also added a bit of Ajaxy fun so that when you click a link it fills in an area below the tag cloud with all the merchants related to that category. Thank goodness for mochikit which makes that kind of thing pretty easy. Go ahead, try it.


© 2006 - 2013 Automatic Romantic | Terms of Use | Privacy Policy | Developer Blog

Web Design Inspired by Andreas Viklund Some icons by Mark James