Minor improvements to navigationoverrides, including admin support and working naviga...
[philo.git] / templatetags / embed.py
1 from django import template
2 from django.contrib.contenttypes.models import ContentType
3 from django.conf import settings
4 from django.template.loader_tags import ExtendsNode, BlockContext, BLOCK_CONTEXT_KEY, TextNode, BlockNode
5 from philo.utils import LOADED_TEMPLATE_ATTR
6
7
8 register = template.Library()
9 EMBED_CONTEXT_KEY = 'embed_context'
10
11
12 class EmbedContext(object):
13         "Inspired by django.template.loader_tags.BlockContext."
14         def __init__(self):
15                 self.embeds = {}
16                 self.rendered = []
17         
18         def add_embeds(self, embeds):
19                 for content_type, embed_list in embeds.iteritems():
20                         if content_type in self.embeds:
21                                 self.embeds[content_type] = embed_list + self.embeds[content_type]
22                         else:
23                                 self.embeds[content_type] = embed_list
24         
25         def get_embed_template(self, embed, context):
26                 """To return a template for an embed node, find the node's position in the stack
27                 and then progress up the stack until a template-defining node is found
28                 """
29                 ct = embed.get_content_type(context)
30                 embeds = self.embeds[ct]
31                 embeds = embeds[:embeds.index(embed)][::-1]
32                 for e in embeds:
33                         template = e.get_template(context)
34                         if template:
35                                 return template
36                 
37                 # No template was found in the current render_context - but perhaps one level up? Or more?
38                 # We may be in an inclusion tag.
39                 self_found = False
40                 for context_dict in context.render_context.dicts[::-1]:
41                         if not self_found:
42                                 if self in context_dict.values():
43                                         self_found = True
44                                         continue
45                         elif EMBED_CONTEXT_KEY not in context_dict:
46                                 continue
47                         else:
48                                 embed_context = context_dict[EMBED_CONTEXT_KEY]
49                                 # We can tell where we are in the list of embeds by which have already been rendered.
50                                 embeds = embed_context.embeds[ct][:len(embed_context.rendered)][::-1]
51                                 for e in embeds:
52                                         template = e.get_template(context)
53                                         if template:
54                                                 return template
55                 
56                 raise IndexError
57
58
59 # Override ExtendsNode render method to have it handle EmbedNodes
60 # similarly to BlockNodes.
61 old_extends_node_init = ExtendsNode.__init__
62
63
64 def get_embed_dict(nodelist):
65         embeds = {}
66         for n in nodelist.get_nodes_by_type(ConstantEmbedNode):
67                 if n.content_type not in embeds:
68                         embeds[n.content_type] = [n]
69                 else:
70                         embeds[n.content_type].append(n)
71         return embeds
72
73
74 def extends_node_init(self, nodelist, *args, **kwargs):
75         self.embeds = get_embed_dict(nodelist)
76         old_extends_node_init(self, nodelist, *args, **kwargs)
77
78
79 def render_extends_node(self, context):
80         compiled_parent = self.get_parent(context)
81         
82         if BLOCK_CONTEXT_KEY not in context.render_context:
83                 context.render_context[BLOCK_CONTEXT_KEY] = BlockContext()
84         block_context = context.render_context[BLOCK_CONTEXT_KEY]
85         
86         if EMBED_CONTEXT_KEY not in context.render_context:
87                 context.render_context[EMBED_CONTEXT_KEY] = EmbedContext()
88         embed_context = context.render_context[EMBED_CONTEXT_KEY]
89         
90         # Add the block nodes from this node to the block context
91         # Do the equivalent for embed nodes
92         block_context.add_blocks(self.blocks)
93         embed_context.add_embeds(self.embeds)
94         
95         # If this block's parent doesn't have an extends node it is the root,
96         # and its block nodes also need to be added to the block context.
97         for node in compiled_parent.nodelist:
98                 # The ExtendsNode has to be the first non-text node.
99                 if not isinstance(node, TextNode):
100                         if not isinstance(node, ExtendsNode):
101                                 blocks = dict([(n.name, n) for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode)])
102                                 block_context.add_blocks(blocks)
103                                 embeds = get_embed_dict(compiled_parent.nodelist)
104                                 embed_context.add_embeds(embeds)
105                         break
106
107         # Call Template._render explicitly so the parser context stays
108         # the same.
109         return compiled_parent._render(context)
110
111
112 ExtendsNode.__init__ = extends_node_init
113 ExtendsNode.render = render_extends_node
114
115
116 class ConstantEmbedNode(template.Node):
117         """Analogous to the ConstantIncludeNode, this node precompiles several variables necessary for correct rendering - namely the referenced instance or the included template."""
118         def __init__(self, content_type, object_pk=None, template_name=None, kwargs=None):
119                 assert template_name is not None or object_pk is not None
120                 self.content_type = content_type
121                 
122                 kwargs = kwargs or {}
123                 for k, v in kwargs.items():
124                         kwargs[k] = v
125                 self.kwargs = kwargs
126                 
127                 if object_pk is not None:
128                         self.instance = self.compile_instance(object_pk)
129                 else:
130                         self.instance = None
131                 
132                 if template_name is not None:
133                         self.template = self.compile_template(template_name[1:-1])
134                 else:
135                         self.template = None
136         
137         def compile_instance(self, object_pk):
138                 self.object_pk = object_pk
139                 model = self.content_type.model_class()
140                 try:
141                         return model.objects.get(pk=object_pk)
142                 except model.DoesNotExist:
143                         if not hasattr(self, 'object_pk') and settings.TEMPLATE_DEBUG:
144                                 # Then it's a constant node.
145                                 raise
146                         return False
147         
148         def get_instance(self, context):
149                 return self.instance
150         
151         def compile_template(self, template_name):
152                 try:
153                         return template.loader.get_template(template_name)
154                 except template.TemplateDoesNotExist:
155                         if not hasattr(self, 'template_name') and settings.TEMPLATE_DEBUG:
156                                 # Then it's a constant node.
157                                 raise
158                         return False
159         
160         def get_template(self, context):
161                 return self.template
162         
163         def get_content_type(self, context):
164                 return self.content_type
165         
166         def check_context(self, context):
167                 if EMBED_CONTEXT_KEY not in context.render_context:
168                         context.render_context[EMBED_CONTEXT_KEY] = EmbedContext()
169                 embed_context = context.render_context[EMBED_CONTEXT_KEY]
170                 
171                 ct = self.get_content_type(context)
172                 if ct not in embed_context.embeds:
173                         embed_context.embeds[ct] = [self]
174                 elif self not in embed_context.embeds[ct]:
175                         embed_context.embeds[ct].append(self)
176         
177         def mark_rendered_for(self, context):
178                 context.render_context[EMBED_CONTEXT_KEY].rendered.append(self)
179         
180         def render(self, context):
181                 self.check_context(context)
182                 
183                 template = self.get_template(context)
184                 if template is not None:
185                         self.mark_rendered_for(context)
186                         if template is False:
187                                 return settings.TEMPLATE_STRING_IF_INVALID
188                         return ''
189                 
190                 # Otherwise an instance should be available. Render the instance with the appropriate template!
191                 instance = self.get_instance(context)
192                 if instance is None or instance is False:
193                         self.mark_rendered_for(context)
194                         return settings.TEMPLATE_STRING_IF_INVALID
195                 
196                 return self.render_instance(context, instance)
197         
198         def render_instance(self, context, instance):
199                 try:
200                         t = context.render_context[EMBED_CONTEXT_KEY].get_embed_template(self, context)
201                 except (KeyError, IndexError):
202                         if settings.TEMPLATE_DEBUG:
203                                 raise
204                         return settings.TEMPLATE_STRING_IF_INVALID
205                 
206                 context.push()
207                 context['embedded'] = instance
208                 kwargs = {}
209                 for k, v in self.kwargs.items():
210                         kwargs[k] = v.resolve(context)
211                 context.update(kwargs)
212                 t_rendered = t.render(context)
213                 context.pop()
214                 self.mark_rendered_for(context)
215                 return t_rendered
216
217
218 class EmbedNode(ConstantEmbedNode):
219         def __init__(self, content_type, object_pk=None, template_name=None, kwargs=None):
220                 assert template_name is not None or object_pk is not None
221                 self.content_type = content_type
222                 self.kwargs = kwargs or {}
223                 
224                 if object_pk is not None:
225                         self.object_pk = object_pk
226                 else:
227                         self.object_pk = None
228                         self.instance = None
229                 
230                 if template_name is not None:
231                         self.template_name = template_name
232                 else:
233                         self.template_name = None
234                         self.template = None
235         
236         def get_instance(self, context):
237                 if self.object_pk is None:
238                         return None
239                 return self.compile_instance(self.object_pk.resolve(context))
240         
241         def get_template(self, context):
242                 if self.template_name is None:
243                         return None
244                 return self.compile_template(self.template_name.resolve(context))
245
246
247 class InstanceEmbedNode(EmbedNode):
248         def __init__(self, instance, kwargs=None):
249                 self.instance = instance
250                 self.kwargs = kwargs or {}
251         
252         def get_template(self, context):
253                 return None
254         
255         def get_instance(self, context):
256                 return self.instance.resolve(context)
257         
258         def get_content_type(self, context):
259                 return ContentType.objects.get_for_model(self.get_instance(context))
260
261
262 def get_embedded(self):
263         return self.template
264
265
266 setattr(ConstantEmbedNode, LOADED_TEMPLATE_ATTR, property(get_embedded))
267
268
269 def get_content_type(bit):
270         try:
271                 app_label, model = bit.split('.')
272         except ValueError:
273                 raise template.TemplateSyntaxError('"%s" template tag expects the first argument to be of the form app_label.model' % tag)
274         try:
275                 ct = ContentType.objects.get(app_label=app_label, model=model)
276         except ContentType.DoesNotExist:
277                 raise template.TemplateSyntaxError('"%s" template tag requires an argument of the form app_label.model which refers to an installed content type (see django.contrib.contenttypes)' % tag)
278         return ct
279
280
281 def do_embed(parser, token):
282         """
283         The {% embed %} tag can be used in two ways:
284         {% embed <app_label>.<model_name> with <template> %} :: Sets which template will be used to render a particular model.
285         {% embed (<app_label>.<model_name> <object_pk> || <instance>) [<argname>=<value> ...] %} :: Embeds the instance specified by the given parameters in the document with the previously-specified template. Any kwargs provided will be passed into the context of the template.
286         """
287         bits = token.split_contents()
288         tag = bits.pop(0)
289         
290         if len(bits) < 1:
291                 raise template.TemplateSyntaxError('"%s" template tag must have at least two arguments.' % tag)
292         
293         if len(bits) == 3 and bits[-2] == 'with':
294                 ct = get_content_type(bits[0])
295                 
296                 if bits[2][0] in ['"', "'"] and bits[2][0] == bits[2][-1]:
297                         return ConstantEmbedNode(ct, template_name=bits[2])
298                 return EmbedNode(ct, template_name=bits[2])
299         
300         # Otherwise they're trying to embed a certain instance.
301         kwargs = {}
302         try:
303                 bit = bits.pop()
304                 while '=' in bit:
305                         k, v = bit.split('=')
306                         kwargs[k] = parser.compile_filter(v)
307                         bit = bits.pop()
308                 bits.append(bit)
309         except IndexError:
310                 raise template.TemplateSyntaxError('"%s" template tag expects at least one non-keyword argument when embedding instances.')
311         
312         if len(bits) == 1:
313                 instance = parser.compile_filter(bits[0])
314                 return InstanceEmbedNode(instance, kwargs)
315         elif len(bits) > 2:
316                 raise template.TemplateSyntaxError('"%s" template tag expects at most 2 non-keyword arguments when embedding instances.')
317         ct = get_content_type(bits[0])
318         pk = bits[1]
319         
320         try:
321                 int(pk)
322         except ValueError:
323                 return EmbedNode(ct, object_pk=parser.compile_filter(pk), kwargs=kwargs)
324         else:
325                 return ConstantEmbedNode(ct, object_pk=pk, kwargs=kwargs)
326
327
328 register.tag('embed', do_embed)