Added a number of counting variables to the context when rendering shipherd navigatio...
[philo.git] / templatetags / collections.py
1 from django import template
2 from django.conf import settings
3 from django.contrib.contenttypes.models import ContentType
4
5
6 register = template.Library()
7
8
9 class MembersofNode(template.Node):
10         def __init__(self, collection, model, as_var):
11                 self.collection = template.Variable(collection)
12                 self.model = model
13                 self.as_var = as_var
14                 
15         def render(self, context):
16                 try:
17                         collection = self.collection.resolve(context)
18                         context[self.as_var] = collection.members.with_model(self.model)
19                 except:
20                         pass
21                 return ''
22
23
24 def do_membersof(parser, token):
25         """
26         {% membersof <collection> with <app_label>.<model_name> as <var> %}
27         """
28         params=token.split_contents()
29         tag = params[0]
30         
31         if len(params) < 6:
32                 raise template.TemplateSyntaxError('"%s" template tag requires six parameters' % tag)
33                 
34         if params[2] != 'with':
35                 raise template.TemplateSyntaxError('"%s" template tag requires the third parameter to be "with"' % tag)
36         
37         try:
38                 app_label, model = params[3].strip('"').split('.')
39                 ct = ContentType.objects.get(app_label=app_label, model=model)
40         except ValueError:
41                 raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument of the form app_label.model (see django.contrib.contenttypes)' % tag)
42         except ContentType.DoesNotExist:
43                 raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument of the form app_label.model which refers to an installed content type (see django.contrib.contenttypes)' % tag)
44                 
45         if params[4] != 'as':
46                 raise template.TemplateSyntaxError('"%s" template tag requires the fifth parameter to be "as"' % tag)
47         
48         return MembersofNode(collection=params[1], model=ct.model_class(), as_var=params[5])
49
50
51 register.tag('membersof', do_membersof)