Code source de django.template.base

"""This is the Django template system.How it works:The Lexer.tokenize() function converts a template string (i.e., a string containingmarkup with custom template tags) to tokens, which can be either plain text(TOKEN_TEXT), variables (TOKEN_VAR) or block statements (TOKEN_BLOCK).The Parser() class takes a list of tokens in its constructor, and its parse()method returns a compiled template -- which is, under the hood, a list ofNode objects.Each Node is responsible for creating some sort of output -- e.g. simple text(TextNode), variable values in a given context (VariableNode), results of basiclogic (IfNode), results of looping (ForNode), or anything else. The core Nodetypes are TextNode, VariableNode, IfNode and ForNode, but plugin modules candefine their own custom node types.Each Node has a render() method, which takes a Context and returns a string ofthe rendered node. For example, the render() method of a Variable Node returnsthe variable's value as a string. The render() method of a ForNode returns therendered output of whatever was inside the loop, recursively.The Template class is a convenient wrapper that takes care of templatecompilation and rendering.Usage:The only thing you should ever use directly in this file is the Template class.Create a compiled template object with a template_string, then call render()with a context. In the compilation stage, the TemplateSyntaxError exceptionwill be raised if the template doesn't have proper syntax.Sample code:>>> from django import template>>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>'>>> t = template.Template(s)(t is now a compiled template, and its render() method can be called multipletimes with multiple contexts)>>> c = template.Context({'test':True, 'varvalue': 'Hello'})>>> t.render(c)'<html><h1>Hello</h1></html>'>>> c = template.Context({'test':False, 'varvalue': 'Hello'})>>> t.render(c)'<html></html>'"""from__future__importunicode_literalsimportinspectimportloggingimportreimportwarningsfromdjango.template.contextimport(# NOQA: imported for backwards compatibilityBaseContext,Context,ContextPopException,RequestContext,)fromdjango.utilsimportsixfromdjango.utils.deprecationimport(DeprecationInstanceCheck,RemovedInDjango20Warning,)fromdjango.utils.encodingimport(force_str,force_text,python_2_unicode_compatible,)fromdjango.utils.formatsimportlocalizefromdjango.utils.htmlimportconditional_escape,escapefromdjango.utils.inspectimportgetargspecfromdjango.utils.safestringimport(EscapeData,SafeData,mark_for_escaping,mark_safe,)fromdjango.utils.textimport(get_text_list,smart_split,unescape_string_literal,)fromdjango.utils.timezoneimporttemplate_localtimefromdjango.utils.translationimportpgettext_lazy,ugettext_lazyfrom.exceptionsimportTemplateSyntaxErrorTOKEN_TEXT=0TOKEN_VAR=1TOKEN_BLOCK=2TOKEN_COMMENT=3TOKEN_MAPPING={TOKEN_TEXT:'Text',TOKEN_VAR:'Var',TOKEN_BLOCK:'Block',TOKEN_COMMENT:'Comment',}# template syntax constantsFILTER_SEPARATOR='|'FILTER_ARGUMENT_SEPARATOR=':'VARIABLE_ATTRIBUTE_SEPARATOR='.'BLOCK_TAG_START='{%'BLOCK_TAG_END='%}'VARIABLE_TAG_START='{{'VARIABLE_TAG_END='}}'COMMENT_TAG_START='{#'COMMENT_TAG_END='#}'TRANSLATOR_COMMENT_MARK='Translators'SINGLE_BRACE_START='{'SINGLE_BRACE_END='}'# what to report as the origin for templates that come from non-loader sources# (e.g. strings)UNKNOWN_SOURCE='<unknown source>'# match a variable or block tag and capture the entire tag, including start/end# delimiterstag_re=(re.compile('(%s.*?%s|%s.*?%s|%s.*?%s)'%(re.escape(BLOCK_TAG_START),re.escape(BLOCK_TAG_END),re.escape(VARIABLE_TAG_START),re.escape(VARIABLE_TAG_END),re.escape(COMMENT_TAG_START),re.escape(COMMENT_TAG_END))))logger=logging.getLogger('django.template')classTemplateEncodingError(Exception):pass@python_2_unicode_compatibleclassVariableDoesNotExist(Exception):def__init__(self,msg,params=()):self.msg=msgself.params=paramsdef__str__(self):returnself.msg%tuple(force_text(p,errors='replace')forpinself.params)

[docs]classTemplate(object):def__init__(self,template_string,origin=None,name=None,engine=None):try:template_string=force_text(template_string)exceptUnicodeDecodeError:raiseTemplateEncodingError("Templates can only be constructed ""from unicode or UTF-8 strings.")# If Template is instantiated directly rather than from an Engine and# exactly one Django template engine is configured, use that engine.# This is required to preserve backwards-compatibility for direct use# e.g. Template('...').render(Context({...}))ifengineisNone:from.engineimportEngineengine=Engine.get_default()iforiginisNone:origin=Origin(UNKNOWN_SOURCE)self.name=nameself.origin=originself.engine=engineself.source=template_stringself.nodelist=self.compile_nodelist()def__iter__(self):fornodeinself.nodelist:forsubnodeinnode:yieldsubnodedef_render(self,context):returnself.nodelist.render(context)

[docs]defrender(self,context):"Display stage -- can be called many times"context.render_context.push()try:ifcontext.templateisNone:withcontext.bind_template(self):context.template_name=self.namereturnself._render(context)else:returnself._render(context)finally:context.render_context.pop()

defcompile_nodelist(self):""" Parse and compile the template source into a nodelist. If debug is True and an exception occurs during parsing, the exception is is annotated with contextual line information where it occurred in the template source. """ifself.engine.debug:lexer=DebugLexer(self.source)else:lexer=Lexer(self.source)tokens=lexer.tokenize()parser=Parser(tokens,self.engine.template_libraries,self.engine.template_builtins,self.origin,)try:returnparser.parse()exceptExceptionase:ifself.engine.debug:e.template_debug=self.get_exception_info(e,e.token)raisedefget_exception_info(self,exception,token):""" Return a dictionary containing contextual line information of where the exception occurred in the template. The following information is provided: message The message of the exception raised. source_lines The lines before, after, and including the line the exception occurred on. line The line number the exception occurred on. before, during, after The line the exception occurred on split into three parts: 1. The content before the token that raised the error. 2. The token that raised the error. 3. The content after the token that raised the error. total The number of lines in source_lines. top The line number where source_lines starts. bottom The line number where source_lines ends. start The start position of the token in the template source. end The end position of the token in the template source. """start,end=token.positioncontext_lines=10line=0upto=0source_lines=[]before=during=after=""fornum,nextinenumerate(linebreak_iter(self.source)):ifstart>=uptoandend<=next:line=numbefore=escape(self.source[upto:start])during=escape(self.source[start:end])after=escape(self.source[end:next])source_lines.append((num,escape(self.source[upto:next])))upto=nexttotal=len(source_lines)top=max(1,line-context_lines)bottom=min(total,line+1+context_lines)# In some rare cases exc_value.args can be empty or an invalid# unicode string.try:message=force_text(exception.args[0])except(IndexError,UnicodeDecodeError):message='(Could not get exception message)'return{'message':message,'source_lines':source_lines[top:bottom],'before':before,'during':during,'after':after,'top':top,'bottom':bottom,'total':total,'line':line,'name':self.origin.name,'start':start,'end':end,}

deflinebreak_iter(template_source):yield0p=template_source.find('\n')whilep>=0:yieldp+1p=template_source.find('\n',p+1)yieldlen(template_source)+1classToken(object):def__init__(self,token_type,contents,position=None,lineno=None):""" A token representing a string from the template. token_type One of TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK, or TOKEN_COMMENT. contents The token source string. position An optional tuple containing the start and end index of the token in the template source. This is used for traceback information when debug is on. lineno The line number the token appears on in the template source. This is used for traceback information and gettext files. """self.token_type,self.contents=token_type,contentsself.lineno=linenoself.position=positiondef__str__(self):token_name=TOKEN_MAPPING[self.token_type]return('<%s token: "%s...">'%(token_name,self.contents[:20].replace('\n','')))defsplit_contents(self):split=[]bits=iter(smart_split(self.contents))forbitinbits:# Handle translation-marked template piecesifbit.startswith(('_("',"_('")):sentinel=bit[2]+')'trans_bit=[bit]whilenotbit.endswith(sentinel):bit=next(bits)trans_bit.append(bit)bit=' '.join(trans_bit)split.append(bit)returnsplitclassLexer(object):def__init__(self,template_string):self.template_string=template_stringself.verbatim=Falsedeftokenize(self):""" Return a list of tokens from a given template_string. """in_tag=Falselineno=1result=[]forbitintag_re.split(self.template_string):ifbit:result.append(self.create_token(bit,None,lineno,in_tag))in_tag=notin_taglineno+=bit.count('\n')returnresultdefcreate_token(self,token_string,position,lineno,in_tag):""" Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ifin_tagandtoken_string.startswith(BLOCK_TAG_START):# The [2:-2] ranges below strip off *_TAG_START and *_TAG_END.# We could do len(BLOCK_TAG_START) to be more "correct", but we've# hard-coded the 2s here for performance. And it's not like# the TAG_START values are going to change anytime, anyway.block_content=token_string[2:-2].strip()ifself.verbatimandblock_content==self.verbatim:self.verbatim=Falseifin_tagandnotself.verbatim:iftoken_string.startswith(VARIABLE_TAG_START):token=Token(TOKEN_VAR,token_string[2:-2].strip(),position,lineno)eliftoken_string.startswith(BLOCK_TAG_START):ifblock_content[:9]in('verbatim','verbatim '):self.verbatim='end%s'%block_contenttoken=Token(TOKEN_BLOCK,block_content,position,lineno)eliftoken_string.startswith(COMMENT_TAG_START):content=''iftoken_string.find(TRANSLATOR_COMMENT_MARK):content=token_string[2:-2].strip()token=Token(TOKEN_COMMENT,content,position,lineno)else:token=Token(TOKEN_TEXT,token_string,position,lineno)returntokenclassDebugLexer(Lexer):deftokenize(self):""" Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so we only use it when debug is True. """lineno=1result=[]upto=0formatchintag_re.finditer(self.template_string):start,end=match.span()ifstart>upto:token_string=self.template_string[upto:start]result.append(self.create_token(token_string,(upto,start),lineno,in_tag=False))lineno+=token_string.count('\n')upto=starttoken_string=self.template_string[start:end]result.append(self.create_token(token_string,(start,end),lineno,in_tag=True))lineno+=token_string.count('\n')upto=endlast_bit=self.template_string[upto:]iflast_bit:result.append(self.create_token(last_bit,(upto,upto+len(last_bit)),lineno,in_tag=False))returnresultclassParser(object):def__init__(self,tokens,libraries=None,builtins=None,origin=None):self.tokens=tokensself.tags={}self.filters={}self.command_stack=[]iflibrariesisNone:libraries={}ifbuiltinsisNone:builtins=[]self.libraries=librariesforbuiltininbuiltins:self.add_library(builtin)self.origin=origindefparse(self,parse_until=None):""" Iterate through the parser tokens and compiles each one into a node. If parse_until is provided, parsing will stop once one of the specified tokens has been reached. This is formatted as a list of tokens, e.g. ['elif', 'else', 'endif']. If no matching token is reached, raise an exception with the unclosed block tag details. """ifparse_untilisNone:parse_until=[]nodelist=NodeList()whileself.tokens:token=self.next_token()# Use the raw values here for TOKEN_* for a tiny performance boost.iftoken.token_type==0:# TOKEN_TEXTself.extend_nodelist(nodelist,TextNode(token.contents),token)eliftoken.token_type==1:# TOKEN_VARifnottoken.contents:raiseself.error(token,'Empty variable tag on line %d'%token.lineno)try:filter_expression=self.compile_filter(token.contents)exceptTemplateSyntaxErrorase:raiseself.error(token,e)var_node=VariableNode(filter_expression)self.extend_nodelist(nodelist,var_node,token)eliftoken.token_type==2:# TOKEN_BLOCKtry:command=token.contents.split()[0]exceptIndexError:raiseself.error(token,'Empty block tag on line %d'%token.lineno)ifcommandinparse_until:# A matching token has been reached. Return control to# the caller. Put the token back on the token list so the# caller knows where it terminated.self.prepend_token(token)returnnodelist# Add the token to the command stack. This is used for error# messages if further parsing fails due to an unclosed block# tag.self.command_stack.append((command,token))# Get the tag callback function from the ones registered with# the parser.try:compile_func=self.tags[command]exceptKeyError:self.invalid_block_tag(token,command,parse_until)# Compile the callback into a node object and add it to# the node list.try:compiled_result=compile_func(self,token)exceptExceptionase:raiseself.error(token,e)self.extend_nodelist(nodelist,compiled_result,token)# Compile success. Remove the token from the command stack.self.command_stack.pop()ifparse_until:self.unclosed_block_tag(parse_until)returnnodelistdefskip_past(self,endtag):whileself.tokens:token=self.next_token()iftoken.token_type==TOKEN_BLOCKandtoken.contents==endtag:returnself.unclosed_block_tag([endtag])defextend_nodelist(self,nodelist,node,token):# Check that non-text nodes don't appear before an extends tag.ifnode.must_be_firstandnodelist.contains_nontext:raiseself.error(token,'%r must be the first tag in the template.'%node,)ifisinstance(nodelist,NodeList)andnotisinstance(node,TextNode):nodelist.contains_nontext=True# Set origin and token here since we can't modify the node __init__()# method.node.token=tokennode.origin=self.originnodelist.append(node)deferror(self,token,e):""" Return an exception annotated with the originating token. Since the parser can be called recursively, check if a token is already set. This ensures the innermost token is highlighted if an exception occurs, e.g. a compile error within the body of an if statement. """ifnotisinstance(e,Exception):e=TemplateSyntaxError(e)ifnothasattr(e,'token'):e.token=tokenreturnedefinvalid_block_tag(self,token,command,parse_until=None):ifparse_until:raiseself.error(token,"Invalid block tag on line %d: '%s', expected %s. Did you ""forget to register or load this tag?"%(token.lineno,command,get_text_list(["'%s'"%pforpinparse_until],'or'),),)raiseself.error(token,"Invalid block tag on line %d: '%s'. Did you forget to register ""or load this tag?"%(token.lineno,command))defunclosed_block_tag(self,parse_until):command,token=self.command_stack.pop()msg="Unclosed tag on line %d: '%s'. Looking for one of: %s."%(token.lineno,command,', '.join(parse_until),)raiseself.error(token,msg)defnext_token(self):returnself.tokens.pop(0)defprepend_token(self,token):self.tokens.insert(0,token)defdelete_first_token(self):delself.tokens[0]defadd_library(self,lib):self.tags.update(lib.tags)self.filters.update(lib.filters)defcompile_filter(self,token):""" Convenient wrapper for FilterExpression """returnFilterExpression(token,self)deffind_filter(self,filter_name):iffilter_nameinself.filters:returnself.filters[filter_name]else:raiseTemplateSyntaxError("Invalid filter: '%s'"%filter_name)# This only matches constant *strings* (things in quotes or marked for# translation). Numbers are treated as variables for implementation reasons# (so that they retain their type when passed to filters).constant_string=r"""(?:%(i18n_open)s%(strdq)s%(i18n_close)s|%(i18n_open)s%(strsq)s%(i18n_close)s|%(strdq)s|%(strsq)s)"""%{'strdq':r'"[^"\\]*(?:\\.[^"\\]*)*"',# double-quoted string'strsq':r"'[^'\\]*(?:\\.[^'\\]*)*'",# single-quoted string'i18n_open':re.escape("_("),'i18n_close':re.escape(")"),}constant_string=constant_string.replace("\n","")filter_raw_string=r"""^(?P<constant>%(constant)s)|^(?P<var>[%(var_chars)s]+|%(num)s)| (?:\s*%(filter_sep)s\s* (?P<filter_name>\w+) (?:%(arg_sep)s (?: (?P<constant_arg>%(constant)s)| (?P<var_arg>[%(var_chars)s]+|%(num)s) ) )? )"""%{'constant':constant_string,'num':r'[-+\.]?\d[\d\.e]*','var_chars':"\w\.",'filter_sep':re.escape(FILTER_SEPARATOR),'arg_sep':re.escape(FILTER_ARGUMENT_SEPARATOR),}filter_re=re.compile(filter_raw_string,re.UNICODE|re.VERBOSE)classFilterExpression(object):""" Parses a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample:: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(token, p) >>> len(fe.filters) 2 >>> fe.var <Variable: 'variable'> """def__init__(self,token,parser):self.token=tokenmatches=filter_re.finditer(token)var_obj=Nonefilters=[]upto=0formatchinmatches:start=match.start()ifupto!=start:raiseTemplateSyntaxError("Could not parse some characters: ""%s|%s|%s"%(token[:upto],token[upto:start],token[start:]))ifvar_objisNone:var,constant=match.group("var","constant")ifconstant:try:var_obj=Variable(constant).resolve({})exceptVariableDoesNotExist:var_obj=NoneelifvarisNone:raiseTemplateSyntaxError("Could not find variable at ""start of %s."%token)else:var_obj=Variable(var)else:filter_name=match.group("filter_name")args=[]constant_arg,var_arg=match.group("constant_arg","var_arg")ifconstant_arg:args.append((False,Variable(constant_arg).resolve({})))elifvar_arg:args.append((True,Variable(var_arg)))filter_func=parser.find_filter(filter_name)self.args_check(filter_name,filter_func,args)filters.append((filter_func,args))upto=match.end()ifupto!=len(token):raiseTemplateSyntaxError("Could not parse the remainder: '%s' ""from '%s'"%(token[upto:],token))self.filters=filtersself.var=var_objdefresolve(self,context,ignore_failures=False):ifisinstance(self.var,Variable):try:obj=self.var.resolve(context)exceptVariableDoesNotExist:ifignore_failures:obj=Noneelse:string_if_invalid=context.template.engine.string_if_invalidifstring_if_invalid:if'%s'instring_if_invalid:returnstring_if_invalid%self.varelse:returnstring_if_invalidelse:obj=string_if_invalidelse:obj=self.varescape_isnt_last_filter=Trueforfunc,argsinself.filters:arg_vals=[]forlookup,arginargs:ifnotlookup:arg_vals.append(mark_safe(arg))else:arg_vals.append(arg.resolve(context))ifgetattr(func,'expects_localtime',False):obj=template_localtime(obj,context.use_tz)ifgetattr(func,'needs_autoescape',False):new_obj=func(obj,autoescape=context.autoescape,*arg_vals)else:new_obj=func(obj,*arg_vals)ifgetattr(func,'is_safe',False)andisinstance(obj,SafeData):obj=mark_safe(new_obj)elifisinstance(obj,EscapeData):withwarnings.catch_warnings():# Ignore mark_for_escaping deprecation as this will be# removed in Django 2.0.warnings.simplefilter('ignore',category=RemovedInDjango20Warning)obj=mark_for_escaping(new_obj)escape_isnt_last_filter=Falseelse:obj=new_objifnotescape_isnt_last_filter:warnings.warn("escape isn't the last filter in %s and will be applied ""immediately in Django 2.0 so the output may change."%[func.__name__forfunc,_inself.filters],RemovedInDjango20Warning,stacklevel=2)returnobjdefargs_check(name,func,provided):provided=list(provided)# First argument, filter input, is implied.plen=len(provided)+1# Check to see if a decorator is providing the real function.func=getattr(func,'_decorated_function',func)args,_,_,defaults=getargspec(func)alen=len(args)dlen=len(defaultsor[])# Not enough OR Too manyifplen<(alen-dlen)orplen>alen:raiseTemplateSyntaxError("%s requires %d arguments, %d provided"%(name,alen-dlen,plen))returnTrueargs_check=staticmethod(args_check)def__str__(self):returnself.tokenclassVariable(object):""" A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':'News'}} >>> Variable('article.section').resolve(c) 'News' >>> Variable('article').resolve(c) {'section': 'News'} >>> class AClass: pass >>> c = AClass() >>> c.article = AClass() >>> c.article.section = 'News' (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.') """def__init__(self,var):self.var=varself.literal=Noneself.lookups=Noneself.translate=Falseself.message_context=Noneifnotisinstance(var,six.string_types):raiseTypeError("Variable must be a string or number, got %s"%type(var))try:# First try to treat this variable as a number.## Note that this could cause an OverflowError here that we're not# catching. Since this should only happen at compile time, that's# probably OK.self.literal=float(var)# So it's a float... is it an int? If the original value contained a# dot or an "e" then it was a float, not an int.if'.'notinvarand'e'notinvar.lower():self.literal=int(self.literal)# "2." is invalidifvar.endswith('.'):raiseValueErrorexceptValueError:# A ValueError means that the variable isn't a number.ifvar.startswith('_(')andvar.endswith(')'):# The result of the lookup should be translated at rendering# time.self.translate=Truevar=var[2:-1]# If it's wrapped with quotes (single or double), then# we're also dealing with a literal.try:self.literal=mark_safe(unescape_string_literal(var))exceptValueError:# Otherwise we'll set self.lookups so that resolve() knows we're# dealing with a bonafide variableifvar.find(VARIABLE_ATTRIBUTE_SEPARATOR+'_')>-1orvar[0]=='_':raiseTemplateSyntaxError("Variables and attributes may ""not begin with underscores: '%s'"%var)self.lookups=tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR))defresolve(self,context):"""Resolve this variable against a given context."""ifself.lookupsisnotNone:# We're dealing with a variable that needs to be resolvedvalue=self._resolve_lookup(context)else:# We're dealing with a literal, so it's already been "resolved"value=self.literalifself.translate:is_safe=isinstance(value,SafeData)msgid=value.replace('%','%%')msgid=mark_safe(msgid)ifis_safeelsemsgidifself.message_context:returnpgettext_lazy(self.message_context,msgid)else:returnugettext_lazy(msgid)returnvaluedef__repr__(self):return"<%s: %r>"%(self.__class__.__name__,self.var)def__str__(self):returnself.vardef_resolve_lookup(self,context):""" Performs resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() instead. """current=contexttry:# catch-all for silent variable failuresforbitinself.lookups:try:# dictionary lookupcurrent=current[bit]# ValueError/IndexError are for numpy.array lookup on# numpy < 1.9 and 1.9+ respectivelyexcept(TypeError,AttributeError,KeyError,ValueError,IndexError):try:# attribute lookup# Don't return class attributes if the class is the context:ifisinstance(current,BaseContext)andgetattr(type(current),bit):raiseAttributeErrorcurrent=getattr(current,bit)except(TypeError,AttributeError)ase:# Reraise an AttributeError raised by a @propertyif(isinstance(e,AttributeError)andnotisinstance(current,BaseContext)andbitindir(current)):raisetry:# list-index lookupcurrent=current[int(bit)]except(IndexError,# list index out of rangeValueError,# invalid literal for int()KeyError,# current is a dict without `int(bit)` keyTypeError):# unsubscriptable objectraiseVariableDoesNotExist("Failed lookup for key ""[%s] in %r",(bit,current))# missing attributeifcallable(current):ifgetattr(current,'do_not_call_in_templates',False):passelifgetattr(current,'alters_data',False):current=context.template.engine.string_if_invalidelse:try:# method call (assuming no args required)current=current()exceptTypeError:try:inspect.getcallargs(current)exceptTypeError:# arguments *were* requiredcurrent=context.template.engine.string_if_invalid# invalid method callelse:raiseexceptExceptionase:template_name=getattr(context,'template_name',None)or'unknown'logger.debug("Exception while resolving variable '%s' in template '%s'.",bit,template_name,exc_info=True,)ifgetattr(e,'silent_variable_failure',False):current=context.template.engine.string_if_invalidelse:raisereturncurrentclassNode(object):# Set this to True for nodes that must be first in the template (although# they can be preceded by text nodes.must_be_first=Falsechild_nodelists=('nodelist',)token=Nonedefrender(self,context):""" Return the node rendered as a string. """passdefrender_annotated(self,context):""" Render the node. If debug is True and an exception occurs during rendering, the exception is annotated with contextual line information where it occurred in the template. For internal usage this method is preferred over using the render method directly. """try:returnself.render(context)exceptExceptionase:ifcontext.template.engine.debugandnothasattr(e,'template_debug'):e.template_debug=context.template.get_exception_info(e,self.token)raisedef__iter__(self):yieldselfdefget_nodes_by_type(self,nodetype):""" Return a list of all nodes (within this node and its nodelist) of the given type """nodes=[]ifisinstance(self,nodetype):nodes.append(self)forattrinself.child_nodelists:nodelist=getattr(self,attr,None)ifnodelist:nodes.extend(nodelist.get_nodes_by_type(nodetype))returnnodesclassNodeList(list):# Set to True the first time a non-TextNode is inserted by# extend_nodelist().contains_nontext=Falsedefrender(self,context):bits=[]fornodeinself:ifisinstance(node,Node):bit=node.render_annotated(context)else:bit=nodebits.append(force_text(bit))returnmark_safe(''.join(bits))defget_nodes_by_type(self,nodetype):"Return a list of all nodes of the given type"nodes=[]fornodeinself:nodes.extend(node.get_nodes_by_type(nodetype))returnnodesclassTextNode(Node):def__init__(self,s):self.s=sdef__repr__(self):rep="<%s: %r>"%(self.__class__.__name__,self.s[:25])returnforce_str(rep,'ascii',errors='replace')defrender(self,context):returnself.sdefrender_value_in_context(value,context):""" Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a unicode object. If value is a string, it is expected to have already been translated. """value=template_localtime(value,use_tz=context.use_tz)value=localize(value,use_l10n=context.use_l10n)value=force_text(value)ifcontext.autoescapeorisinstance(value,EscapeData):returnconditional_escape(value)else:returnvalueclassVariableNode(Node):def__init__(self,filter_expression):self.filter_expression=filter_expressiondef__repr__(self):return"<Variable Node: %s>"%self.filter_expressiondefrender(self,context):try:output=self.filter_expression.resolve(context)exceptUnicodeDecodeError:# Unicode conversion can fail sometimes for reasons out of our# control (e.g. exception rendering). In that case, we fail# quietly.return''returnrender_value_in_context(output,context)# Regex for token keyword argumentskwarg_re=re.compile(r"(?:(\w+)=)?(.+)")deftoken_kwargs(bits,parser,support_legacy=False):""" A utility method for parsing token keyword arguments. :param bits: A list containing remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments will be removed from this list. :param support_legacy: If set to true ``True``, the legacy format ``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1`` format is allowed. :returns: A dictionary of the arguments retrieved from the ``bits`` token list. There is no requirement for all remaining token ``bits`` to be keyword arguments, so the dictionary will be returned as soon as an invalid argument format is reached. """ifnotbits:return{}match=kwarg_re.match(bits[0])kwarg_format=matchandmatch.group(1)ifnotkwarg_format:ifnotsupport_legacy:return{}iflen(bits)<3orbits[1]!='as':return{}kwargs={}whilebits:ifkwarg_format:match=kwarg_re.match(bits[0])ifnotmatchornotmatch.group(1):returnkwargskey,value=match.groups()delbits[:1]else:iflen(bits)<3orbits[1]!='as':returnkwargskey,value=bits[2],bits[0]delbits[:3]kwargs[key]=parser.compile_filter(value)ifbitsandnotkwarg_format:ifbits[0]!='and':returnkwargsdelbits[:1]returnkwargs