25Nov/080
Django tag cloud
Ciao a tutti.
In questo post vorrei mostrare uno snippet veramente utile per visualizzare una tag cloud in una applicazione Django.
Supponiamo di avere nella nostra applicazione una relazione n-n tra un modello Post e un modello Tag.
Vogliamio dunque visualizzare nel nostro layout tutta la lista dei tag associati ai vari post, evidenziando quelli maggiormente utilizzati.
Per prima cosa e’ necessario registrare un nuovo templatetag:
from django.template import Library, Node
from myapp.models import Tag, Post
import random
register = Library()
maxsize =180 # maximum size of the most popular tag
minsize = 75 # minimum size of the least popular tag
class LatestTagsNode(Node):
def gen_clouds(self):
tag_list=Tag.objects.all()
if tag_list:
max1=max([int(tag_item.posts.count()) for tag_item in tag_list])
for i in range(tag_list.count()):
size =int(round(int(tag_list[i].posts.count())*maxsize/max1))
if size<minsize:
size=minsize
cloudsize =str(size) +"%"
tag_list[i].cloudsize=cloudsize
return tag_list
def render(self, context):
self.__init__()
context['content_tagclouds'] = self.gen_clouds()
return ''
def get_latest_cloudtag(parser, token):
return LatestTagsNode()
get_latest_cloudtag= register.tag(get_latest_cloudtag)
from myapp.models import Tag, Post
import random
register = Library()
maxsize =180 # maximum size of the most popular tag
minsize = 75 # minimum size of the least popular tag
class LatestTagsNode(Node):
def gen_clouds(self):
tag_list=Tag.objects.all()
if tag_list:
max1=max([int(tag_item.posts.count()) for tag_item in tag_list])
for i in range(tag_list.count()):
size =int(round(int(tag_list[i].posts.count())*maxsize/max1))
if size<minsize:
size=minsize
cloudsize =str(size) +"%"
tag_list[i].cloudsize=cloudsize
return tag_list
def render(self, context):
self.__init__()
context['content_tagclouds'] = self.gen_clouds()
return ''
def get_latest_cloudtag(parser, token):
return LatestTagsNode()
get_latest_cloudtag= register.tag(get_latest_cloudtag)
A questo punto, nel nostro template, bastera’ richiamare il templatetag in questo modo:
<div>
{% load tags %}
{% get_latest_cloudtag %}
{% for tag in content_tagclouds %}
< a href="{{ tag.get_absolute_url }}"
style="font-size:{{ tag.cloudsize }};
text-align:left;"> {{ tag.name }}</a>
{% endfor %}
</div>
{% load tags %}
{% get_latest_cloudtag %}
{% for tag in content_tagclouds %}
< a href="{{ tag.get_absolute_url }}"
style="font-size:{{ tag.cloudsize }};
text-align:left;"> {{ tag.name }}</a>
{% endfor %}
</div>