Merge branch 'develop' into fast_containers
[philo.git] / philo / templatetags / containers.py
1 """
2 The container 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 from django.core.exceptions import ObjectDoesNotExist
10 from django.db.models import Q
11 from django.utils.safestring import SafeUnicode, mark_safe
12
13
14 register = template.Library()
15
16
17 CONTAINER_CONTEXT_KEY = 'philo_container_context'
18
19
20 class ContainerContext(object):
21         def __init__(self, page):
22                 contentlet_specs, contentreference_specs = page.template.containers
23                 
24                 contentlets = page.contentlets.filter(name__in=contentlet_specs)
25                 self.contentlets = dict(((c.name, c) for c in contentlets))
26                 
27                 q = Q()
28                 for name, ct in contentreference_specs.items():
29                         q |= Q(name=name, content_type=ct)
30                 references = page.contentreferences.filter(q)
31                 self.references = dict(((c.name, c) for c in references))
32
33
34 class ContainerNode(template.Node):
35         def __init__(self, name, references=None, as_var=None):
36                 self.name = name
37                 self.as_var = as_var
38                 self.references = references
39         
40         def render(self, context):
41                 content = settings.TEMPLATE_STRING_IF_INVALID
42                 if 'page' in context:
43                         container_content = self.get_container_content(context)
44                 else:
45                         container_content = None
46                 
47                 if self.as_var:
48                         context[self.as_var] = container_content
49                         return ''
50                 
51                 if not container_content:
52                         return ''
53                 
54                 return container_content
55         
56         def get_container_content(self, context):
57                 try:
58                         container_context = context.render_context[CONTAINER_CONTEXT_KEY]
59                 except KeyError:
60                         container_context = ContainerContext(context['page'])
61                         context.render_context[CONTAINER_CONTEXT_KEY] = container_context
62                 
63                 if self.references:
64                         # Then it's a content reference.
65                         try:
66                                 contentreference = container_context.references[(self.name, self.references)]
67                         except KeyError:
68                                 content = ''
69                         else:
70                                 content = contentreference.content
71                 else:
72                         # Otherwise it's a contentlet.
73                         try:
74                                 contentlet = container_context.contentlets[self.name]
75                         except KeyError:
76                                 content = ''
77                         else:
78                                 content = contentlet.content
79                 return content
80
81
82 @register.tag
83 def container(parser, token):
84         """
85         If a template using this tag is used to render a :class:`.Page`, that :class:`.Page` will have associated content which can be set in the admin interface. If a content type is referenced, then a :class:`.ContentReference` object will be created; otherwise, a :class:`.Contentlet` object will be created.
86         
87         Usage::
88         
89                 {% container <name> [[references <app_label>.<model_name>] as <variable>] %}
90         
91         """
92         params = token.split_contents()
93         if len(params) >= 2:
94                 tag = params[0]
95                 name = params[1].strip('"')
96                 references = None
97                 as_var = None
98                 if len(params) > 2:
99                         remaining_tokens = params[2:]
100                         while remaining_tokens:
101                                 option_token = remaining_tokens.pop(0)
102                                 if option_token == 'references':
103                                         try:
104                                                 app_label, model = remaining_tokens.pop(0).strip('"').split('.')
105                                                 references = ContentType.objects.get_by_natural_key(app_label, model)
106                                         except IndexError:
107                                                 raise template.TemplateSyntaxError('"%s" template tag option "references" requires an argument specifying a content type' % tag)
108                                         except ValueError:
109                                                 raise template.TemplateSyntaxError('"%s" template tag option "references" requires an argument of the form app_label.model (see django.contrib.contenttypes)' % tag)
110                                         except ObjectDoesNotExist:
111                                                 raise template.TemplateSyntaxError('"%s" template tag option "references" requires an argument of the form app_label.model which refers to an installed content type (see django.contrib.contenttypes)' % tag)
112                                 elif option_token == 'as':
113                                         try:
114                                                 as_var = remaining_tokens.pop(0)
115                                         except IndexError:
116                                                 raise template.TemplateSyntaxError('"%s" template tag option "as" requires an argument specifying a variable name' % tag)
117                         if references and not as_var:
118                                 raise template.TemplateSyntaxError('"%s" template tags using "references" option require additional use of the "as" option specifying a variable name' % tag)
119                 return ContainerNode(name, references, as_var)
120                 
121         else: # error
122                 raise template.TemplateSyntaxError('"%s" template tag provided without arguments (at least one required)' % tag)