Eliminated unnecessary ContentType queries that used applabel/model-based lookups.
[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 """
5
6 from django import template
7 from django.conf import settings
8 from django.contrib.contenttypes.models import ContentType
9
10
11 register = template.Library()
12
13
14 class MembersofNode(template.Node):
15         def __init__(self, collection, model, as_var):
16                 self.collection = template.Variable(collection)
17                 self.model = model
18                 self.as_var = as_var
19                 
20         def render(self, context):
21                 try:
22                         collection = self.collection.resolve(context)
23                         context[self.as_var] = collection.members.with_model(self.model)
24                 except:
25                         pass
26                 return ''
27
28
29 @register.tag
30 def membersof(parser, token):
31         """
32         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.
33         
34         Usage::
35         
36                 {% membersof <collection> with <app_label>.<model_name> as <var> %}
37         
38         """
39         params=token.split_contents()
40         tag = params[0]
41         
42         if len(params) < 6:
43                 raise template.TemplateSyntaxError('"%s" template tag requires six parameters' % tag)
44                 
45         if params[2] != 'with':
46                 raise template.TemplateSyntaxError('"%s" template tag requires the third parameter to be "with"' % tag)
47         
48         try:
49                 app_label, model = params[3].strip('"').split('.')
50                 ct = ContentType.objects.get_by_natural_key(app_label, model)
51         except ValueError:
52                 raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument of the form app_label.model (see django.contrib.contenttypes)' % tag)
53         except ContentType.DoesNotExist:
54                 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)
55                 
56         if params[4] != 'as':
57                 raise template.TemplateSyntaxError('"%s" template tag requires the fifth parameter to be "as"' % tag)
58         
59         return MembersofNode(collection=params[1], model=ct.model_class(), as_var=params[5])