Added {% include_string %} tag to allow passing of context from templates to template...
authorStephen Burrows <stephen.r.burrows@gmail.com>
Wed, 17 Nov 2010 18:51:13 +0000 (13:51 -0500)
committerStephen Burrows <stephen.r.burrows@gmail.com>
Mon, 29 Nov 2010 18:31:54 +0000 (13:31 -0500)
templatetags/include_string.py [new file with mode: 0644]

diff --git a/templatetags/include_string.py b/templatetags/include_string.py
new file mode 100644 (file)
index 0000000..260dcff
--- /dev/null
@@ -0,0 +1,38 @@
+from django import template
+from django.conf import settings
+
+
+register = template.Library()
+
+
+class IncludeStringNode(template.Node):
+       """The passed variable is expected to be a string of template code to be rendered with
+       the current context."""
+       def __init__(self, string):
+               self.string = string
+       
+       def render(self, context):
+               try:
+                       t = template.Template(self.string.resolve(context))
+                       return t.render(context)
+               except template.TemplateSyntaxError:
+                       if settings.TEMPLATE_DEBUG:
+                               raise
+                       return settings.TEMPLATE_STRING_IF_INVALID
+               except:
+                       return settings.TEMPLATE_STRING_IF_INVALID
+
+
+def do_include_string(parser, token):
+       """
+       Include a flat string by interpreting it as a template.
+       {% include_string <template_code> %}
+       """
+       bits = token.split_contents()
+       if len(bits) != 2:
+               raise TemplateSyntaxError("%r tag takes one argument: the template string to be included" % bits[0])
+       string = parser.compile_filter(bits[1])
+       return IncludeStringNode(string)
+
+
+register.tag('include_string', do_include_string)
\ No newline at end of file