Django

Code

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

File django-include-tag-svn880.diff, 2.4 kB (added by L.Plant.98@cantab.net, 3 years ago)

Patch updated for subversion rev 880 plus

  • django/core/template/defaulttags.py

    old new  
    227227                return '' # Fail silently for invalid included templates. 
    228228        return output 
    229229 
     230class ConstantIncludeNode(Node): 
     231    def __init__(self, template_path): 
     232        from django.core.template.loader import get_template 
     233        try:  
     234            t = get_template(template_path) 
     235            self.nodelist = t.nodelist 
     236        except Exception, e: 
     237            self.nodelist = None 
     238 
     239    def render(self, context): 
     240        if self.nodelist: 
     241            return self.nodelist.render(context) 
     242        else: 
     243            return '' 
     244 
     245class IncludeNode(Node): 
     246     
     247    def __init__(self, template_path_var): 
     248        self.template_path_var = template_path_var 
     249 
     250    def render(self, context): 
     251        from django.core.template.loader import get_template 
     252        try: 
     253            template_path = template.resolve_variable(self.template_path_var, context) 
     254            print "IncludeNode rendering %s" % template_path  
     255            t = get_template(template_path) 
     256            return t.render(context) 
     257        except Exception, e: 
     258            return '' # Fail silently for invalid included templates. 
     259 
    230260class LoadNode(Node): 
    231261    def __init__(self, taglib): 
    232262        self.taglib = taglib 
     
    608638            raise TemplateSyntaxError, "Second (optional) argument to %s tag must be 'parsed'" % bits[0] 
    609639    return SsiNode(bits[1], parsed) 
    610640 
     641def do_include(parser, token): 
     642    """ 
     643    Loads a template using standard resolution mechanisms, and renders it in the current context.      
     644    """ 
     645    bits = token.contents.split() 
     646    if len(bits) != 2: 
     647        raise TemplateSyntaxError, "'include' tag takes one argument: the path to the template to be included" 
     648     
     649    path = bits[1] 
     650    if path[0] in ('"', "'") and path[-1] == path[0]: 
     651        return ConstantIncludeNode(path[1:-1])  
     652    return IncludeNode(bits[1]) 
     653 
    611654def do_load(parser, token): 
    612655    """ 
    613656    Load a custom template tag set. 
     
    763806register_tag('ifnotequal', lambda parser, token: do_ifequal(parser, token, True)) 
    764807register_tag('if', do_if) 
    765808register_tag('ifchanged', do_ifchanged) 
     809register_tag('include', do_include) 
    766810register_tag('regroup', do_regroup) 
    767811register_tag('ssi', do_ssi) 
    768812register_tag('load', do_load)