1 from django import template
2 from django.conf import settings
3 from django.contrib.contenttypes.models import ContentType
4 from django.template.loader_tags import ExtendsNode, BlockContext, BLOCK_CONTEXT_KEY, TextNode, BlockNode
6 from philo.utils import LOADED_TEMPLATE_ATTR
9 register = template.Library()
10 EMBED_CONTEXT_KEY = 'embed_context'
13 class EmbedContext(object):
14 "Inspired by django.template.loader_tags.BlockContext."
19 def add_embeds(self, embeds):
20 for content_type, embed_list in embeds.iteritems():
21 if content_type in self.embeds:
22 self.embeds[content_type] = embed_list + self.embeds[content_type]
24 self.embeds[content_type] = embed_list
26 def get_embed_template(self, embed, context):
27 """To return a template for an embed node, find the node's position in the stack
28 and then progress up the stack until a template-defining node is found
30 ct = embed.get_content_type(context)
31 embeds = self.embeds[ct]
32 embeds = embeds[:embeds.index(embed)][::-1]
34 template = e.get_template(context)
38 # No template was found in the current render_context - but perhaps one level up? Or more?
39 # We may be in an inclusion tag.
41 for context_dict in context.render_context.dicts[::-1]:
43 if self in context_dict.values():
46 elif EMBED_CONTEXT_KEY not in context_dict:
49 embed_context = context_dict[EMBED_CONTEXT_KEY]
50 # We can tell where we are in the list of embeds by which have already been rendered.
51 embeds = embed_context.embeds[ct][:len(embed_context.rendered)][::-1]
53 template = e.get_template(context)
60 # Override ExtendsNode render method to have it handle EmbedNodes
61 # similarly to BlockNodes.
62 old_extends_node_init = ExtendsNode.__init__
65 def get_embed_dict(embed_list, context):
68 ct = e.get_content_type(context)
70 # Then the embed doesn't exist for this context.
79 def extends_node_init(self, nodelist, *args, **kwargs):
80 self.embed_list = nodelist.get_nodes_by_type(ConstantEmbedNode)
81 old_extends_node_init(self, nodelist, *args, **kwargs)
84 def render_extends_node(self, context):
85 compiled_parent = self.get_parent(context)
86 embeds = get_embed_dict(self.embed_list, context)
88 if BLOCK_CONTEXT_KEY not in context.render_context:
89 context.render_context[BLOCK_CONTEXT_KEY] = BlockContext()
90 block_context = context.render_context[BLOCK_CONTEXT_KEY]
92 if EMBED_CONTEXT_KEY not in context.render_context:
93 context.render_context[EMBED_CONTEXT_KEY] = EmbedContext()
94 embed_context = context.render_context[EMBED_CONTEXT_KEY]
96 # Add the block nodes from this node to the block context
97 # Do the equivalent for embed nodes
98 block_context.add_blocks(self.blocks)
99 embed_context.add_embeds(embeds)
101 # If this block's parent doesn't have an extends node it is the root,
102 # and its block nodes also need to be added to the block context.
103 for node in compiled_parent.nodelist:
104 # The ExtendsNode has to be the first non-text node.
105 if not isinstance(node, TextNode):
106 if not isinstance(node, ExtendsNode):
107 blocks = dict([(n.name, n) for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode)])
108 block_context.add_blocks(blocks)
109 embeds = get_embed_dict(compiled_parent.nodelist.get_nodes_by_type(ConstantEmbedNode), context)
110 embed_context.add_embeds(embeds)
113 # Explicitly render all direct embed children of this node.
115 for node in self.nodelist:
116 if isinstance(node, ConstantEmbedNode):
119 # Call Template._render explicitly so the parser context stays
121 return compiled_parent._render(context)
124 ExtendsNode.__init__ = extends_node_init
125 ExtendsNode.render = render_extends_node
128 class ConstantEmbedNode(template.Node):
129 """Analogous to the ConstantIncludeNode, this node precompiles several variables necessary for correct rendering - namely the referenced instance or the included template."""
130 def __init__(self, content_type, object_pk=None, template_name=None, kwargs=None):
131 assert template_name is not None or object_pk is not None
132 self.content_type = content_type
134 kwargs = kwargs or {}
135 for k, v in kwargs.items():
139 if object_pk is not None:
140 self.instance = self.compile_instance(object_pk)
144 if template_name is not None:
145 self.template = self.compile_template(template_name[1:-1])
149 def compile_instance(self, object_pk):
150 model = self.content_type.model_class()
152 return model.objects.get(pk=object_pk)
153 except model.DoesNotExist:
154 if not hasattr(self, 'object_pk') and settings.TEMPLATE_DEBUG:
155 # Then it's a constant node.
159 def get_instance(self, context):
162 def compile_template(self, template_name):
164 return template.loader.get_template(template_name)
165 except template.TemplateDoesNotExist:
166 if hasattr(self, 'template') and settings.TEMPLATE_DEBUG:
167 # Then it's a constant node.
171 def get_template(self, context):
174 def get_content_type(self, context):
175 return self.content_type
177 def check_context(self, context):
178 if EMBED_CONTEXT_KEY not in context.render_context:
179 context.render_context[EMBED_CONTEXT_KEY] = EmbedContext()
180 embed_context = context.render_context[EMBED_CONTEXT_KEY]
182 ct = self.get_content_type(context)
183 if ct not in embed_context.embeds:
184 embed_context.embeds[ct] = [self]
185 elif self not in embed_context.embeds[ct]:
186 embed_context.embeds[ct].append(self)
188 def mark_rendered_for(self, context):
189 context.render_context[EMBED_CONTEXT_KEY].rendered.append(self)
191 def render(self, context):
192 self.check_context(context)
194 template = self.get_template(context)
195 if template is not None:
196 self.mark_rendered_for(context)
197 if template is False:
198 return settings.TEMPLATE_STRING_IF_INVALID
201 # Otherwise an instance should be available. Render the instance with the appropriate template!
202 instance = self.get_instance(context)
203 if instance is None or instance is False:
204 self.mark_rendered_for(context)
205 return settings.TEMPLATE_STRING_IF_INVALID
207 return self.render_instance(context, instance)
209 def render_instance(self, context, instance):
211 t = context.render_context[EMBED_CONTEXT_KEY].get_embed_template(self, context)
212 except (KeyError, IndexError):
213 self.mark_rendered_for(context)
214 return settings.TEMPLATE_STRING_IF_INVALID
217 context['embedded'] = instance
218 for k, v in self.kwargs.items():
219 context[k] = v.resolve(context)
220 t_rendered = t.render(context)
222 self.mark_rendered_for(context)
226 class EmbedNode(ConstantEmbedNode):
227 def __init__(self, content_type, object_pk=None, template_name=None, kwargs=None):
228 assert template_name is not None or object_pk is not None
229 self.content_type = content_type
230 self.kwargs = kwargs or {}
232 if object_pk is not None:
233 self.object_pk = object_pk
235 self.object_pk = None
237 if template_name is not None:
238 self.template_name = template_name
240 self.template_name = None
242 def get_instance(self, context):
243 if self.object_pk is None:
245 return self.compile_instance(self.object_pk.resolve(context))
247 def get_template(self, context):
248 if self.template_name is None:
250 return self.compile_template(self.template_name.resolve(context))
253 class InstanceEmbedNode(EmbedNode):
254 def __init__(self, instance, kwargs=None):
255 self.instance = instance
256 self.kwargs = kwargs or {}
258 def get_template(self, context):
261 def get_instance(self, context):
262 return self.instance.resolve(context)
264 def get_content_type(self, context):
265 instance = self.get_instance(context)
268 return ContentType.objects.get_for_model(instance)
271 def get_embedded(self):
275 setattr(ConstantEmbedNode, LOADED_TEMPLATE_ATTR, property(get_embedded))
278 def parse_content_type(bit, tagname):
280 app_label, model = bit.split('.')
282 raise template.TemplateSyntaxError('"%s" template tag expects the first argument to be of the form app_label.model' % tagname)
284 ct = ContentType.objects.get(app_label=app_label, model=model)
285 except ContentType.DoesNotExist:
286 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)' % tagname)
290 def do_embed(parser, token):
292 The {% embed %} tag can be used in two ways:
293 {% embed <app_label>.<model_name> with <template> %} :: Sets which template will be used to render a particular model.
294 {% 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.
296 bits = token.split_contents()
300 raise template.TemplateSyntaxError('"%s" template tag must have at least two arguments.' % tag)
302 if len(bits) == 3 and bits[-2] == 'with':
303 ct = parse_content_type(bits[0], tag)
305 if bits[2][0] in ['"', "'"] and bits[2][0] == bits[2][-1]:
306 return ConstantEmbedNode(ct, template_name=bits[2])
307 return EmbedNode(ct, template_name=bits[2])
309 # Otherwise they're trying to embed a certain instance.
314 k, v = bit.split('=')
315 kwargs[k] = parser.compile_filter(v)
319 raise template.TemplateSyntaxError('"%s" template tag expects at least one non-keyword argument when embedding instances.')
322 instance = parser.compile_filter(bits[0])
323 return InstanceEmbedNode(instance, kwargs)
325 raise template.TemplateSyntaxError('"%s" template tag expects at most 2 non-keyword arguments when embedding instances.')
326 ct = parse_content_type(bits[0], tag)
332 return EmbedNode(ct, object_pk=parser.compile_filter(pk), kwargs=kwargs)
334 return ConstantEmbedNode(ct, object_pk=pk, kwargs=kwargs)
337 register.tag('embed', do_embed)