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
8 register = template.Library()
9 EMBED_CONTEXT_KEY = 'embed_context'
12 class EmbedContext(object):
13 "Inspired by django.template.loader_tags.BlockContext."
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]
23 self.embeds[content_type] = embed_list
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
29 ct = embed.get_content_type(context)
30 embeds = self.embeds[ct]
31 embeds = embeds[:embeds.index(embed)][::-1]
33 template = e.get_template(context)
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.
40 for context_dict in context.render_context.dicts[::-1]:
42 if self in context_dict.values():
45 elif EMBED_CONTEXT_KEY not in context_dict:
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]
52 template = e.get_template(context)
59 # Override ExtendsNode render method to have it handle EmbedNodes
60 # similarly to BlockNodes.
61 old_extends_node_init = ExtendsNode.__init__
64 def get_embed_dict(nodelist):
66 for n in nodelist.get_nodes_by_type(ConstantEmbedNode):
67 if n.content_type not in embeds:
68 embeds[n.content_type] = [n]
70 embeds[n.content_type].append(n)
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)
79 def render_extends_node(self, context):
80 compiled_parent = self.get_parent(context)
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]
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]
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)
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)
107 # Call Template._render explicitly so the parser context stays
109 return compiled_parent._render(context)
112 ExtendsNode.__init__ = extends_node_init
113 ExtendsNode.render = render_extends_node
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
122 kwargs = kwargs or {}
123 for k, v in kwargs.items():
127 if object_pk is not None:
128 self.instance = self.compile_instance(object_pk)
132 if template_name is not None:
133 self.template = self.compile_template(template_name[1:-1])
137 def compile_instance(self, object_pk):
138 self.object_pk = object_pk
139 model = self.content_type.model_class()
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.
148 def get_instance(self, context):
151 def compile_template(self, template_name):
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.
160 def get_template(self, context):
163 def get_content_type(self, context):
164 return self.content_type
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]
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)
177 def mark_rendered_for(self, context):
178 context.render_context[EMBED_CONTEXT_KEY].rendered.append(self)
180 def render(self, context):
181 self.check_context(context)
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
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
196 return self.render_instance(context, instance)
198 def render_instance(self, context, instance):
200 t = context.render_context[EMBED_CONTEXT_KEY].get_embed_template(self, context)
201 except (KeyError, IndexError):
202 if settings.TEMPLATE_DEBUG:
204 return settings.TEMPLATE_STRING_IF_INVALID
207 context['embedded'] = instance
209 for k, v in self.kwargs.items():
210 kwargs[k] = v.resolve(context)
211 context.update(kwargs)
212 t_rendered = t.render(context)
214 self.mark_rendered_for(context)
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 {}
224 if object_pk is not None:
225 self.object_pk = object_pk
227 self.object_pk = None
230 if template_name is not None:
231 self.template_name = template_name
233 self.template_name = None
236 def get_instance(self, context):
237 if self.object_pk is None:
239 return self.compile_instance(self.object_pk.resolve(context))
241 def get_template(self, context):
242 if self.template_name is None:
244 return self.compile_template(self.template_name.resolve(context))
247 class InstanceEmbedNode(EmbedNode):
248 def __init__(self, instance, kwargs=None):
249 self.instance = instance
250 self.kwargs = kwargs or {}
252 def get_template(self, context):
255 def get_instance(self, context):
256 return self.instance.resolve(context)
258 def get_content_type(self, context):
259 return ContentType.objects.get_for_model(self.get_instance(context))
262 def get_embedded(self):
266 setattr(ConstantEmbedNode, LOADED_TEMPLATE_ATTR, property(get_embedded))
269 def get_content_type(bit):
271 app_label, model = bit.split('.')
273 raise template.TemplateSyntaxError('"%s" template tag expects the first argument to be of the form app_label.model' % tag)
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)
281 def do_embed(parser, token):
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.
287 bits = token.split_contents()
291 raise template.TemplateSyntaxError('"%s" template tag must have at least two arguments.' % tag)
293 if len(bits) == 3 and bits[-2] == 'with':
294 ct = get_content_type(bits[0])
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])
300 # Otherwise they're trying to embed a certain instance.
305 k, v = bit.split('=')
306 kwargs[k] = parser.compile_filter(v)
310 raise template.TemplateSyntaxError('"%s" template tag expects at least one non-keyword argument when embedding instances.')
313 instance = parser.compile_filter(bits[0])
314 return InstanceEmbedNode(instance, kwargs)
316 raise template.TemplateSyntaxError('"%s" template tag expects at most 2 non-keyword arguments when embedding instances.')
317 ct = get_content_type(bits[0])
323 return EmbedNode(ct, object_pk=parser.compile_filter(pk), kwargs=kwargs)
325 return ConstantEmbedNode(ct, object_pk=pk, kwargs=kwargs)
328 register.tag('embed', do_embed)