Merge branch 'master' into gilbert
[philo.git] / templatetags / include_string.py
1 from django import template
2 from django.conf import settings
3
4
5 register = template.Library()
6
7
8 class IncludeStringNode(template.Node):
9         """The passed variable is expected to be a string of template code to be rendered with
10         the current context."""
11         def __init__(self, string):
12                 self.string = string
13         
14         def render(self, context):
15                 try:
16                         t = template.Template(self.string.resolve(context))
17                         return t.render(context)
18                 except template.TemplateSyntaxError:
19                         if settings.TEMPLATE_DEBUG:
20                                 raise
21                         return settings.TEMPLATE_STRING_IF_INVALID
22                 except:
23                         return settings.TEMPLATE_STRING_IF_INVALID
24
25
26 def do_include_string(parser, token):
27         """
28         Include a flat string by interpreting it as a template.
29         {% include_string <template_code> %}
30         """
31         bits = token.split_contents()
32         if len(bits) != 2:
33                 raise TemplateSyntaxError("%r tag takes one argument: the template string to be included" % bits[0])
34         string = parser.compile_filter(bits[1])
35         return IncludeStringNode(string)
36
37
38 register.tag('include_string', do_include_string)