Ticket #598: django-include-tag-4.diff

File django-include-tag-4.diff, 2.0 KB (added by jhf@…, 19 years ago)

Fix minor bugs to work properly with revision 1080

  • django/core/template/loader.py

     
    160160                parent_block.nodelist = block_node.nodelist
    161161        return compiled_parent.render(context)
    162162
     163class ConstantIncludeNode(Node):
     164    def __init__(self, template_path):
     165        try:
     166            t = get_template(template_path)
     167            self.nodelist = t.nodelist
     168        except Exception, e:
     169            pass
     170
     171    def render(self, context):
     172        if hasattr(self, 'nodelist'):
     173            return self.nodelist.render(context)
     174        else:
     175            return ''
     176
     177class IncludeNode(Node):
     178    def __init__(self, template_path_var):
     179        self.template_path_var = template_path_var
     180
     181    def render(self, context):
     182         try:
     183             template_path = resolve_variable_with_filters(self.template_path_var, context)
     184             t = get_template(template_path)
     185             return t.render(context)
     186         except Exception, e:
     187             return '' # Fail silently for invalid included templates.
     188
    163189def do_block(parser, token):
    164190    """
    165191    Define a block that can be overridden by child templates.
     
    202228        raise TemplateSyntaxError, "'%s' cannot appear more than once in the same template" % bits[0]
    203229    return ExtendsNode(nodelist, parent_name, parent_name_var)
    204230
     231def do_include(parser, token):
     232    """
     233    Loads a template using standard resolution mechanisms, and renders it in the current context.
     234    """
     235    bits = token.contents.split()
     236    if len(bits) != 2:
     237        raise TemplateSyntaxError, "'include' tag takes one argument: the path to the template to be included"
     238
     239    path = bits[1]
     240    if path[0] in ('"', "'") and path[-1] == path[0]:
     241        return ConstantIncludeNode(path[1:-1])
     242    return IncludeNode(bits[1])
     243
    205244register_tag('block', do_block)
    206245register_tag('extends', do_extends)
     246register_tag('include', do_include)
Back to Top