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:

@staticmethod
def generateSpans():
        counts = session.query(Tag, 
                func.count(Tag.id)).join(blog_tags).group_by(Tag).all()
        
        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)))
                else:
                        scaled.append((tag, 1))

        return scaled

In the view:

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

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:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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