我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.template.Node()。
def handle_token(cls, parser, token): """ Class method to parse prefix node and return a Node. """ bits = token.split_contents() if len(bits) < 2: raise template.TemplateSyntaxError( "'%s' takes at least one argument (path to file)" % bits[0]) path = parser.compile_filter(bits[1]) if len(bits) >= 2 and bits[-2] == 'as': varname = bits[3] else: varname = None return cls(varname, path)
def handle_token(cls, parser, token): """Class method to parse render_comment_form and return a Node.""" tokens = token.split_contents() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_form for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_form for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) )
def handle_token(cls, parser, token): """Class method to parse render_comment_list and return a Node.""" tokens = token.split_contents() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_list for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_list for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) )
def handle_token(cls, parser, token): """ Class method to parse and return a Node. """ bits = token.split_contents() args_count = len(bits) - 1 if args_count >= 2 and bits[-2] == 'as': as_var = bits[-1] args_count -= 2 else: as_var = None if args_count != cls.args_count: arg_list = ' '.join(['[arg]' * cls.args_count]) raise TemplateSyntaxError("Accepted formats {%% %(tagname)s " "%(args)s %%} or {%% %(tagname)s %(args)s as [var] %%}" % {'tagname': bits[0], 'args': arg_list}) args = [parser.compile_filter(token) for token in bits[1:args_count + 1]] return cls(args, varname=as_var)
def __repr__(self): return "<GetAdminLog Node>"
def handle_token(cls, parser, token, name): """ Class method to parse prefix node and return a Node. """ # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments tokens = token.contents.split() if len(tokens) > 1 and tokens[1] != 'as': raise template.TemplateSyntaxError( "First argument in '%s' must be 'as'" % tokens[0]) if len(tokens) > 1: varname = tokens[2] else: varname = None return cls(varname, name)
def urlcompass_step(parser, token): """returns object of __UrlCompassStepNode subclass of django template node object This functions assumes urlcompass_show is already used in the template. hence, it access session data sets maintained by urlcompass_show: :param parser: django parser object :param token: django token object :returns: __UrlCompassStepNode :rtype: django_template.Node :Example: {% urlcompass_step <view> %} """ # analyse toekn for start and wep overrides parts=token.split_contents() if len(parts) != 1: raise django_template.TemplateSyntaxError("'urlcompass_step' accepts one and only one argument: {% url_compass_step <view> %}") view=parts[0].strip() return __UrlCompassStepNode(view)
def get_stack_calls(): stack = [] currentframe = inspect.currentframe() if currentframe is None: return stack try: stackframes = inspect.getouterframes(currentframe) except IndexError: # ???????? ?????? Jinja2 stackframes = traceback.extract_stack() for record in stackframes[2:]: filename, lineno, funcname, line = record if filename.startswith(BASE_PATTERN) and 'devserver' not in filename: filename = filename[len(BASE_PATTERN):] caller = '%s (func %r, line %s)' % (filename, funcname, lineno) stack.append(caller) else: for record in stackframes[2:]: frame, filename, lineno, funcname, lines, index = record if filename in (TEMPLATE_BASE, TEMPLATE_DEBUG): # ????? ?? ??????? node = frame.f_locals.get('node') or frame.f_locals.get('self') if isinstance(node, Node): loader = node.source[0] offsets = node.source[1] with open(loader.name, newline='') as source: start = source.read(offsets[0]) line_num = start.count('\n') + 1 token = source.read(offsets[1] - offsets[0]) caller = '%s (node %r, line %s)' % (loader.loadname, token, line_num) stack.append(caller) break elif filename.startswith(BASE_PATTERN) and 'devserver' not in filename: # ????? ?? ???? filename = filename[len(BASE_PATTERN):] caller = '%s (func %r, line %s)' % (filename, funcname, lineno) stack.append(caller) return reversed(stack)
def __repr__(self): return "<GetAssigedToUser Node>"
def pagenav(page_obj, is_paginated, paginator): # Display page navigation for given list of objects return { 'page_obj': page_obj, 'is_paginated': is_paginated, 'paginator': paginator } #@register.tag #def pagenav(parser, token): ## This version uses a regular expression to parse tag contents. #try: ## Splitting by None == splitting by spaces. #tag_name, page_obj, is_paginated, paginator = token.contents.split() #except ValueError: #raise template.TemplateSyntaxError( #"%r tag requires 3 arguments" % token.contents.split()[0] #) #return PagenavNode(page_obj, is_paginated, paginator) #class PagenavNode(template.Node): #def __init__(self, page_obj, is_paginated, paginator): #self.page_obj = template.Variable(page_obj) #self.is_paginated = template.Variable(is_paginated) #self.paginator = template.Variable(paginator) #def render(self, context): #t = context.template.engine.get_template('students/pagination.html') #context['navigation'] = t.render(template.Context({ #'page_obj': self.page_obj.resolve(context), #'is_paginated': self.is_paginated.resolve(context), #'paginator': self.paginator.resolve(context)} #)) #return ''
def handle_token(cls, parser, token): """Class method to parse get_comment_list/count/form and return a Node.""" tokens = token.split_contents() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% get_whatever for obj as varname %} if len(tokens) == 5: if tokens[3] != 'as': raise template.TemplateSyntaxError("Third argument in %r must be 'as'" % tokens[0]) return cls( object_expr = parser.compile_filter(tokens[2]), as_varname = tokens[4], ) # {% get_whatever for app.model pk as varname %} elif len(tokens) == 6: if tokens[4] != 'as': raise template.TemplateSyntaxError("Fourth argument in %r must be 'as'" % tokens[0]) return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]), as_varname = tokens[5] ) else: raise template.TemplateSyntaxError("%r tag requires 4 or 5 arguments" % tokens[0])
def urlcompass_show(parser, token): """returns object of __UrlCompassShowNode subclass of django template node object This functions analyzes settings to configure __UrlCompassShowNode object: :param parser: django parser object :param token: django token object :returns: __UrlCompassShowNode :rtype: django_template.Node :Example: {{ urlcompass_show }} """ local_settings={} local_settings['start']=URLCOMPASS.get('start',) local_settings['sep']=URLCOMPASS.get('sep',) local_settings['end']=URLCOMPASS.get('end',) local_settings['root_name']=URLCOMPASS.get('root_name',) local_settings['template']=URLCOMPASS.get('template',) local_settings['unique']=URLCOMPASS.get('unique',) html_id=local_settings['html_id']= URLCOMPASS.get('html_id', '') html_class=local_settings['html_class']= URLCOMPASS.get('html_class', '') local_settings['rename']= URLCOMPASS.get('rename', '') # analyse toekn for start and wep overrides parts=token.split_contents() if len(parts) > 0: parts=[part.partition('=') for part in parts if part != 'urlcompass_show'] parts=dict([(name.strip(),adopt_html_attr_value(name, value)) for name, _, value in parts]) else: parts={} # check for extra keys availible_keys=set(local_settings.keys()) received_keys=set(parts.keys()) extra=received_keys.difference(availible_keys) if len(extra) >0: raise django_template.TemplateSyntaxError("Unknown attributes for 'urlcompass_show': {}".format(extra)) for name, value in parts.items(): if name in ['start', 'sep', 'end', 'rename', 'root_name', 'template', 'html_id', 'html_class']: if name not in 'rename': local_settings[name]=value else: local_settings[name]=eval(value) if html_class: local_settings['html_class']='class="{}"'.format(html_class) if html_id: local_settings['html_id']='id="{}"'.format(html_id) return __UrlCompassShowNode(settings=local_settings)