django-tagging clouds template tag

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from django.db.models import get_model
from django.template import Library, Node, TemplateSyntaxError
from apps.tagging.models import Tag

register = Library()

class TagsCloudForModelNode(Node):
    def __init__(self, model, varname, step):
        self.varname, self.step = varname, step
        self.model = get_model(*model.split('.'))

    def render(self, context):
        context[self.varname] = Tag.objects.cloud_for_model(self.model,
                                                            self.step)
        return ''

def do_tags_cloud_for_model(parser, token):
    """
    Retrieves a tag cloud for the given model

    Example usage::

        {% tags_cloud_for_model app.Model as object_list %}
        {% tags_cloud_for_model articles.Article as object_list step 6 %}
    """
    step = 4
    bits = token.contents.split()
    if len(bits) < 4:
        raise TemplateSyntaxError('%s tag requires three arguments' % bits[0])
    if bits[2] != 'as':
        raise TemplateSyntaxError("second argument to %s tag must be 'as'" % bits[0])
    if len(bits) > 4:
        if bits[4] != 'step':
            raise TemplateSyntaxError("optional fourth argument to %s tag must\
                                       be 'step'" % bits[0])
        try:
            step = int(bits[5])
        except IndexError:
            raise TemplateSyntaxError("optional fifth argument after step is \
                                       required")
        except ValueError:
            raise TemplateSyntaxError("optional fifth argument after step is \
                                       not an integer")
    return TagsCloudForModelNode(bits[1], bits[3], step)

register.tag('tags_cloud_for_model', do_tags_cloud_for_model)

More like this

  1. Cloud Tag template example by ramdas 6 years, 5 months ago
  2. Clouds Tag by ramdas 6 years, 5 months ago
  3. Clouds Tag by ramdas 6 years, 5 months ago
  4. simple tag-cloud Template Tag by metty 4 years, 7 months ago
  5. Display arbitrary models by bjornkri 5 years, 9 months ago

Comments

goober (on January 8, 2008):

I am a django newbie and I am trying to integrate this with my current django blog app. My question is the "how to". I created a templatetag in the blog directory and created a tag file aptly name cloud.py. I also added the {% tags_cloud_for_model articles.Article as object_list %} {% tags_cloud_for_model articles.Article as object_list step 6 %} in my base.html.

I can't seem to get the tags to display in my blog. What gives?

Regards.

#

brsma (on April 14, 2009):

Did you also register your template tag in your template with {% load … %}?

#

(Forgotten your password?)