1 from django import template
2 from django.conf import settings
3 from django.utils.safestring import SafeUnicode, mark_safe
4 from django.core.exceptions import ObjectDoesNotExist
5 from django.contrib.contenttypes.models import ContentType
8 register = template.Library()
11 class ContainerNode(template.Node):
12 def __init__(self, name, references=None, as_var=None):
15 self.references = references
17 def render(self, context):
18 content = settings.TEMPLATE_STRING_IF_INVALID
20 container_content = self.get_container_content(context)
22 container_content = None
25 context[self.as_var] = container_content
28 if not container_content:
31 return container_content
33 def get_container_content(self, context):
34 page = context['page']
37 contentreference = page.contentreferences.get(name__exact=self.name, content_type=self.references)
38 content = contentreference.content
39 except ObjectDoesNotExist:
43 contentlet = page.contentlets.get(name__exact=self.name)
44 if contentlet.dynamic:
46 content = mark_safe(template.Template(contentlet.content, name=contentlet.name).render(context))
47 except template.TemplateSyntaxError, error:
49 content = ('[Error parsing contentlet \'%s\': %s]' % (self.name, error))
51 content = contentlet.content
52 except ObjectDoesNotExist:
57 def do_container(parser, token):
59 {% container <name> [[references <type>] as <variable>] %}
61 params = token.split_contents()
64 name = params[1].strip('"')
68 remaining_tokens = params[2:]
69 while remaining_tokens:
70 option_token = remaining_tokens.pop(0)
71 if option_token == 'references':
73 app_label, model = remaining_tokens.pop(0).strip('"').split('.')
74 references = ContentType.objects.get(app_label=app_label, model=model)
76 raise template.TemplateSyntaxError('"%s" template tag option "references" requires an argument specifying a content type' % tag)
78 raise template.TemplateSyntaxError('"%s" template tag option "references" requires an argument of the form app_label.model (see django.contrib.contenttypes)' % tag)
79 except ObjectDoesNotExist:
80 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)
81 elif option_token == 'as':
83 as_var = remaining_tokens.pop(0)
85 raise template.TemplateSyntaxError('"%s" template tag option "as" requires an argument specifying a variable name' % tag)
86 if references and not as_var:
87 raise template.TemplateSyntaxError('"%s" template tags using "references" option require additional use of the "as" option specifying a variable name' % tag)
88 return ContainerNode(name, references, as_var)
91 raise template.TemplateSyntaxError('"%s" template tag provided without arguments (at least one required)' % tag)
94 register.tag('container', do_container)