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)
23 context[self.as_var] = container_content
26 if not container_content:
29 return container_content
31 def get_container_content(self, context):
32 page = context['page']
35 contentreference = page.contentreferences.get(name__exact=self.name, content_type=self.references)
36 content = contentreference.content
37 except ObjectDoesNotExist:
41 contentlet = page.contentlets.get(name__exact=self.name)
42 if contentlet.dynamic:
44 content = mark_safe(template.Template(contentlet.content, name=contentlet.name).render(context))
45 except template.TemplateSyntaxError, error:
47 content = ('[Error parsing contentlet \'%s\': %s]' % (self.name, error))
49 content = contentlet.content
50 except ObjectDoesNotExist:
55 def do_container(parser, token):
57 {% container <name> [[references <type>] as <variable>] %}
59 params = token.split_contents()
62 name = params[1].strip('"')
66 remaining_tokens = params[2:]
67 while remaining_tokens:
68 option_token = remaining_tokens.pop(0)
69 if option_token == 'references':
71 app_label, model = remaining_tokens.pop(0).strip('"').split('.')
72 references = ContentType.objects.get(app_label=app_label, model=model)
74 raise template.TemplateSyntaxError('"%s" template tag option "references" requires an argument specifying a content type' % tag)
76 raise template.TemplateSyntaxError('"%s" template tag option "references" requires an argument of the form app_label.model (see django.contrib.contenttypes)' % tag)
77 except ObjectDoesNotExist:
78 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)
79 elif option_token == 'as':
81 as_var = remaining_tokens.pop(0)
83 raise template.TemplateSyntaxError('"%s" template tag option "as" requires an argument specifying a variable name' % tag)
84 if references and not as_var:
85 raise template.TemplateSyntaxError('"%s" template tags using "references" option require additional use of the "as" option specifying a variable name' % tag)
86 return ContainerNode(name, references, as_var)
89 raise template.TemplateSyntaxError('"%s" template tag provided without arguments (at least one required)' % tag)
92 register.tag('container', do_container)