Skip to content
This repository
Browse code

Adding render_template template tag.

It's just like an include tag but instead of pointing to a direct *.html
file you point to a directory and the filename is derived from the
object's content type.
  • Loading branch information...
commit 57c317fda3600f817b6dab5198fbf15a0dc38a88 1 parent 43508fd
Nathan Borror authored March 18, 2011

Showing 1 changed file with 50 additions and 0 deletions. Show diff stats Hide diff stats

  1. 50  basic/tools/templatetags/objectutils.py
50  basic/tools/templatetags/objectutils.py
... ...
@@ -0,0 +1,50 @@
  1
+from django import template
  2
+from django.template.loader import render_to_string
  3
+from django.template.defaultfilters import slugify
  4
+
  5
+from basic.tools.templatetags.utils import parse_ttag
  6
+
  7
+register = template.Library()
  8
+
  9
+
  10
+class RenderTemplateNode(template.Node):
  11
+    def __init__(self, object_name, template_dir):
  12
+        self.object_name = object_name
  13
+        self.template_dir = template_dir.rstrip('/').strip('"').strip("'")
  14
+
  15
+    def render(self, context):
  16
+        try:
  17
+            obj = template.resolve_variable(self.object_name, context)
  18
+            template_name = '%s.%s.html' % (obj._meta.app_label, obj._meta.module_name)
  19
+            template_list = [
  20
+                '%s/%s' % (self.template_dir, template_name),
  21
+                '%s/default.html' % self.template_dir
  22
+            ]
  23
+            context['object'] = obj
  24
+            return render_to_string(template_list, context)
  25
+        except AttributeError:
  26
+            if (type(obj) in (int, unicode, str)):
  27
+                return obj
  28
+            return ''
  29
+        except template.VariableDoesNotExist:
  30
+            return ''
  31
+
  32
+
  33
+@register.tag()
  34
+def render_template(parser, token):
  35
+    """
  36
+    Returns the proper template based on the objects content_type. If an
  37
+    template doesn't exist it'll fallback to default.html.
  38
+
  39
+    Syntax:
  40
+
  41
+        {% render_template for [object] in [path to templates] %}
  42
+
  43
+    Usage:
  44
+
  45
+        {% render_template for entry in "includes/lists" %}
  46
+    """
  47
+    tags = parse_ttag(token, ['for', 'in'])
  48
+    if len(tags) != 3:
  49
+        raise template.TemplateSyntaxError, '%r tag has invalid arguments' % tags['tag_name']
  50
+    return RenderTemplateNode(object_name=tags['for'], template_dir=tags['in'])

0 notes on commit 57c317f

Please sign in to comment.
Something went wrong with that request. Please try again.