62d6138133eb6a17b7daadb43adf82d80f3f52ba
[philo.git] / philo / templatetags / collections.py
1 """
2 The collection template tags are automatically included as builtins if :mod:`philo` is an installed app.
3
4 .. templatetag:: membersof
5
6 membersof
7 ---------
8
9 Given a collection and a content type, sets the results of :meth:`collection.members.with_model <.CollectionMemberManager.with_model>` as a variable in the context.
10
11 Usage::
12
13         {% membersof <collection> with <app_label>.<model_name> as <var> %}
14
15 """
16
17 from django import template
18 from django.conf import settings
19 from django.contrib.contenttypes.models import ContentType
20
21
22 register = template.Library()
23
24
25 class MembersofNode(template.Node):
26         def __init__(self, collection, model, as_var):
27                 self.collection = template.Variable(collection)
28                 self.model = model
29                 self.as_var = as_var
30                 
31         def render(self, context):
32                 try:
33                         collection = self.collection.resolve(context)
34                         context[self.as_var] = collection.members.with_model(self.model)
35                 except:
36                         pass
37                 return ''
38
39
40 def do_membersof(parser, token):
41         """
42         {% membersof <collection> with <app_label>.<model_name> as <var> %}
43         
44         """
45         params=token.split_contents()
46         tag = params[0]
47         
48         if len(params) < 6:
49                 raise template.TemplateSyntaxError('"%s" template tag requires six parameters' % tag)
50                 
51         if params[2] != 'with':
52                 raise template.TemplateSyntaxError('"%s" template tag requires the third parameter to be "with"' % tag)
53         
54         try:
55                 app_label, model = params[3].strip('"').split('.')
56                 ct = ContentType.objects.get(app_label=app_label, model=model)
57         except ValueError:
58                 raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument of the form app_label.model (see django.contrib.contenttypes)' % tag)
59         except ContentType.DoesNotExist:
60                 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)
61                 
62         if params[4] != 'as':
63                 raise template.TemplateSyntaxError('"%s" template tag requires the fifth parameter to be "as"' % tag)
64         
65         return MembersofNode(collection=params[1], model=ct.model_class(), as_var=params[5])
66
67
68 register.tag('membersof', do_membersof)