Last active
August 29, 2015 14:25
-
-
Save IlianIliev/fc5603fbec7345dd54d1 to your computer and use it in GitHub Desktop.
TagCloud
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ul class="tag-cloud"> | |
{% for tag in tags %} | |
<li class="{{ tag.style_class }}"> | |
<a href="{% url 'tag-detail' tag.slug %}">{{ tag }}</a> | |
</li> | |
{% endfor %} | |
</ul> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
from django.db.models import Count, Max | |
from classytags.core import Tag as ClassyTag | |
from static_blog.models import Tag | |
register = template.Library() | |
class TagCloud(ClassyTag): | |
name = 'tag_cloud' | |
def render_tag(self, context): | |
tags_with_count = Tag.objects.annotate(count=Count('articles'), last_used=Max('articles__date_published'))\ | |
.order_by('-count', '-last_used') | |
# tags_with_count = sorted(tags_with_count, key=lambda i: i.count, reverse=True) | |
max_count = tags_with_count[0].count | |
min_count = tags_with_count[30].count | |
tags_with_count = [tag for tag in tags_with_count if tag.count >= min_count][:50] | |
styles = [] | |
for x in range(1, 12): | |
style = 'size{}'.format(x) | |
styles.append(style) | |
if x >= 8: | |
style += '-plus' | |
styles.append(style) | |
styles = {index: value for index, value in enumerate(styles)} | |
counts_per_group = max_count / float(len(styles)) | |
for tag in tags_with_count: | |
index = int(round(tag.count / counts_per_group)) | |
tag.style_class = styles[index - 1] | |
t = template.loader.get_template('blog/tag_cloud.html') | |
tags_with_count.sort(key=lambda tag: tag.name) | |
return t.render(template.Context({'tags': tags_with_count})) | |
register.tag(TagCloud) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment