Blog tags in Python

Creating the blog tags for this website was a bit tricky because I wasn’t sure how to make the tags have different sizes according to their significance. I started off with 5 spans and ordered the tags in terms of frequency and divided them equally into the spans. However tags are not evenly distributed, so instead I calculated the normalized weight of the tag according to the others, and made the font size a percentage of that.

In the model:

def generateSpans():
        counts = session.query(Tag, 
        smallest = min(count for (tag, count) in counts)
        scale = max(count for (tag, count) in counts) - smallest

        scaled = []
        for tag, count in counts:
                if scale != 0:
                        scaled.append((tag, (count - smallest)/float(scale)))
                        scaled.append((tag, 1))

        return scaled

In the view:

% for tag, weight in tags:
        <span style="font-size: ${int(70 + (80 * weight))|h}%"><a href=
        "${'tag.entries', dict(|h}">${|h}</a> </span>
% endfor

It looks pretty good when there are at least 3 different weightings as you can see to the right.

EDIT in 2021: As you can no longer see the tags as this website has moved to WordPress, a screenshot is here:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s