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

File django-include-tag-2.diff, 2.1 KB (added by rjwittams, 10 years ago)

updated patch - moved tag to template/loaders.py along with other loader tags.

  • 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            self.nodelist = None
     170
     171    def render(self, context):
     172        if 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(self.template_path_var, context)
     184             print "IncludeNode rendering %s" % template_path
     185             t = template_loader.get_template(template_path)
     186             return t.render(context)
     187         except Exception, e:
     188             return '' # Fail silently for invalid included templates.
     189
     190
    163191def do_block(parser, token):
    164192    """
    165193    Define a block that can be overridden by child templates.
     
    202230        raise TemplateSyntaxError, "'%s' cannot appear more than once in the same template" % bits[0]
    203231    return ExtendsNode(nodelist, parent_name, parent_name_var)
    204232
     233def do_include(parser, token):
     234    """
     235    Loads a template using standard resolution mechanisms, and renders it in the current context.
     236    """
     237    bits = token.contents.split()
     238    if len(bits) != 2:
     239        raise TemplateSyntaxError, "'include' tag takes one argument: the path to the template to be included"
     240
     241    path = bits[1]
     242    if path[0] in ('"', "'") and path[-1] == path[0]:
     243        return ConstantIncludeNode(path[1:-1])
     244    return IncludeNode(bits[1])
     245
    205246register_tag('block', do_block)
    206247register_tag('extends', do_extends)
     248register_tag('include', do_include)
Back to Top