def test_render_non_iterable(self): model = generate_random_model() nodelist = NodeList() nodelist.append(layout_helpers.RenderNextNode("'full_page'")) node = layout_helpers.RenderIterNode(Variable("list"), nodelist) with self.assertRaises(TypeError): rendered = node.render(Context({"list": model}))
def test_render_one_element(self): model = generate_random_model() nodelist = NodeList() nodelist.append(layout_helpers.RenderNextNode("'full_page'")) node = layout_helpers.RenderIterNode(Variable("list"), nodelist) rendered = node.render(Context({"list": [model]})) self.assertTrue(re.search(model.title, rendered))
def render(self, context): if 'forloop' in context: parentloop = context['forloop'] else: parentloop = {} context.push() try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) if len_values < 1: context.pop() return self.nodelist_empty.render(context) nodelist = NodeList() if self.is_reversed: values = reversed(values) unpack = len(self.loopvars) > 1 # Create a forloop value in the context. We'll update counters on each # iteration just below. loop_dict = context['forloop'] = {'parentloop': parentloop} for i, item in enumerate(values): # Shortcuts for current loop iteration number. loop_dict['counter0'] = i loop_dict['counter'] = i+1 # Reverse counter iteration numbers. loop_dict['revcounter'] = len_values - i loop_dict['revcounter0'] = len_values - i - 1 # Boolean values designating first and last times through loop. loop_dict['first'] = (i == 0) loop_dict['last'] = (i == len_values - 1) pop_context = False if unpack: # If there are multiple loop variables, unpack the item into # them. try: unpacked_vars = dict(zip(self.loopvars, item)) except TypeError: pass else: pop_context = True context.update(unpacked_vars) else: context[self.loopvars[0]] = item for node in self.nodelist_loop: nodelist.append(node.render(context)) if pop_context: # The loop variables were pushed on to the context so pop them # off again. This is necessary because the tag lets the length # of loopvars differ to the length of each set of items and we # don't want to leave any vars from the previous loop on the # context. context.pop() context.pop() return nodelist.render(context)
def render(self, context): nodelist = NodeList() context.push() try: start = self.start.resolve(context) except VariableDoesNotExist: return '' except AttributeError: start = self.start try: end = self.end.resolve(context) except VariableDoesNotExist: return '' except AttributeError: end = self.end try: step = self.step.resolve(context) except VariableDoesNotExist: return '' except AttributeError: step = self.step for i in range(start, end, step): context[self.var_name] = i for node in self.nodelist_loop: nodelist.append(node.render(context)) context.pop() return nodelist.render(context)
def render(self, context): nodelist = NodeList() context.push() try: start = self.start.resolve(context) except VariableDoesNotExist: return '' except AttributeError: start = self.start try: end = self.end.resolve(context) except VariableDoesNotExist: return '' except AttributeError: end = self.end try: step = self.step.resolve(context) except VariableDoesNotExist: return '' except AttributeError: step = self.step for i in xrange(start, end+1, step): context[self.var_name] = i for node in self.nodelist_loop: nodelist.append(node.render(context)) context.pop() return nodelist.render(context)
def render(self, context): #resolve cube from context try: cube = self.cube.resolve(context, False) except VariableDoesNotExist: return '' #resolve dimensions dimensions = [] for dimension in self.dimensions: matched = re.match('(?P<quote>"|\')(?P<literal>\w+)(?P=quote)', dimension) if matched: dimensions.append(str(matched.group('literal'))) else: try: dimensions.append(str(Variable(dimension).resolve(context))) except VariableDoesNotExist: return '' #loop subcubes and render nodes nodelist = NodeList() for subcube in cube.subcubes(*dimensions): context[self.subcube_var] = subcube for node in self.nodelist: nodelist.append(node.render(context)) return nodelist.render(context)
def render (self, context): nodelist = NodeList () for i in range (int(self.value)): context['percentage'] = {'iter': i} for node in self.nodelist_loop: nodelist.append (node.render(context)) return nodelist.render (context)
def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None): self.loopvars, self.sequence = loopvars, sequence self.is_reversed = is_reversed self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList() else: self.nodelist_empty = nodelist_empty
def render(self, context): if (type(self.value) == StringType): context[self.key] = self.value else: nodelist = NodeList() for node in self.value: nodelist.append(node.render(context)) context[self.key] = nodelist.render(context) return ""
def __init__(self, loopvars_list, sequence_list, is_reversed_list, nodelist_loop, nodelist_empty=None, zip_func=None): self.loopvars_list, self.sequence_list = loopvars_list, sequence_list self.is_reversed_list = is_reversed_list self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList() else: self.nodelist_empty = nodelist_empty self.zip_func = zip_func
def do_render(self, context, sequence): nodelist = NodeList() context.push() for item in sequence: context[self.repeatvar.token] = item for node in self.nodelist: nodelist.append(node.render(context)) context.pop() return nodelist.render(context)
def render_mixers(self, context): nodelist = NodeList() inner_nodelist = self.inner_nodelist context.push() for mixer in self.mixers: context['mixer'] = mixer.template.render(context) nodelist.append(inner_nodelist.render(context)) context.pop() return nodelist.render(context)
def labjs(parser, token): """ Renders a labjs queue from linked js. Syntax:: {% labjs %} <html of linked JS> {% endlabjs %} Examples:: {% labjs %} <script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.5.2.min.js"> </script> {% wait %} <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.formset.min.js"> </script> <script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"> </script> {% endlabjs %} Which would be rendered something like:: <script type="text/javascript"> $LAB.queueScript("/static/js/jquery-1.5.2.min.js") .queueScript("/static/js/jquery.formset.min.js") .queueScript("/jsi18n/"); </script> """ nodelist = NodeList() while True: chunk = parser.parse(('endlabjs', 'wait')) ptoken = parser.next_token() if ptoken.contents == 'wait': chunk.append(Wait()) nodelist.extend(chunk) elif ptoken.contents == 'endlabjs': nodelist.extend(chunk) break return LabjsNode(nodelist)
def test_render_multiple_elements_with_extra_nexts(self): models = [generate_random_model() for i in range(2)] nodelist = NodeList() nodelist.append(layout_helpers.RenderNextNode("'full_page'")) nodelist.append(layout_helpers.RenderNextNode("'full_page'")) nodelist.append(layout_helpers.RenderNextNode("'show_request'")) nodelist.append(layout_helpers.RenderNextNode("'show_request'")) node = layout_helpers.RenderIterNode(Variable("list"), nodelist) rendered = node.render(Context({"list": models})) self.assertTrue(re.search(models[0].title, rendered)) self.assertTrue(re.search(models[1].title, rendered)) self.assertFalse(re.search('request', rendered))
def render(self, context, depth=0, values=False): nodelist = NodeList() if 'recurseloop' in context: parentloop = context['recurseloop'] else: parentloop = {} context.push() # On the first recursion pass, we have no values if not values: try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) # Create a recurseloop value in the context. We'll update counters on each iteration just below. loop_dict = context['recurseloop'] = {'parent': parentloop} loop_dict['depth'] = depth + 1 loop_dict['depth0'] = depth for i, item in enumerate(values): # Add the additional arguments to the context # They come in the form of {'name':(initial,increment)} # As for now only numbers are supported, but also strings can be multiplied for k, v in self.kwargs.iteritems(): context[k] = v[0] + v[1] * depth # Shortcuts for current loop iteration number. loop_dict['counter0'] = i loop_dict['counter'] = i + 1 # Boolean values designating first and last times through loop. loop_dict['first'] = (i == 0) loop_dict['last'] = (i == len_values - 1) context[self.loopvar] = item for node in self.nodelist_first: nodelist.append(node.render(context)) if len(getattr(item, self.children_name)): nodelist.append( self.render(context, depth + 1, getattr(item, self.children_name))) for node in self.nodelist_second: nodelist.append(node.render(context)) context.pop() return nodelist.render(context)
def __init__(self, name, nodelist, parent=None, check_node=None): self.name, self.nodelist, self.parent = name, nodelist, parent self.original_nodelist = NodeList() self.final_nodelist = NodeList() self.original_nodelist.extend( self.nodelist ) self.final_nodelist.extend( self.nodelist ) self.check_node = check_node self.index = None for i, node in enumerate( nodelist ): if isinstance(node, self.check_node.__class__): if node.filter_expression.token == self.check_node.filter_expression.token: self.index = i break
def render(self, context): nodelist = NodeList() if 'forloop' in context: parentloop = context['forloop'] else: parentloop = {} context.push() try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) if self.reversed: values = reversed(values) unpack = len(self.loopvars) > 1 for i, item in enumerate(values): context['forloop'] = { # Shortcuts for current loop iteration number. 'counter0': i, 'counter': i+1, # Reverse counter iteration numbers. 'revcounter': len_values - i, 'revcounter0': len_values - i - 1, # Boolean values designating first and last times through loop. 'first': (i == 0), 'last': (i == len_values - 1), 'parentloop': parentloop, } if unpack: # If there are multiple loop variables, unpack the item into # them. context.update(dict(zip(self.loopvars, item))) else: context[self.loopvars[0]] = item for node in self.nodelist_loop: nodelist.append(node.render(context)) if unpack: # The loop variables were pushed on to the context so pop them # off again. This is necessary because the tag lets the length # of loopvars differ to the length of each set of items and we # don't want to leave any vars from the previous loop on the # context. context.pop() context.pop() return nodelist.render(context)
def test_state_is_not_set_for_poll_box_in_first_of_double_renders(self): settings.DOUBLE_RENDER = True user = User.objects.create(username='******') Vote.objects.create(poll=self.poll, user=user) box = Poll.box_class(self.poll, 'name', NodeList()) box.prepare(Context({'request': build_request(user=user)})) tools.assert_equals(None, box.state)
def do_if(parser, token): """ Template tag {% pyif %} Supports: 1. ==, != 2. not .... 3. v in (1,"y",z) 4. <=, <, >=, > 5. nesting (True and (False or (True or False))) How to use it: {% pyif i == 1 or (5 >= i and i != 7) and user.first_name in ('John', 'Jacob') %} {% else %} {% endif %} """ bits = token.contents.split(None, 1) if len(bits) != 2: raise TemplateSyntaxError, "'%' statement requires at least one argument" % TAGNAME expression = bits[1] variables = set([ parser.compile_filter(x) for x in variable_re.findall(expression) if x not in ('and', 'or', 'not', 'in') and not string_re.match(x) ]) nodelist_true = parser.parse(('else', 'endif')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endif', )) parser.delete_first_token() else: nodelist_false = NodeList() return IfNode(expression, variables, nodelist_true, nodelist_false)
class ThumbnailNode(ThumbnailNodeBase): child_nodelists = ('nodelist_file', 'nodelist_empty') error_msg = ('Syntax error. Expected: ``thumbnail source geometry ' '[key1=val1 key2=val2...] as var``') def __init__(self, parser, token): bits = token.split_contents() if len(bits) < 5 or bits[-2] != 'as': raise TemplateSyntaxError(self.error_msg) self.file_ = parser.compile_filter(bits[1]) self.geometry = parser.compile_filter(bits[2]) self.options = [] for bit in bits[3:-2]: m = kw_pat.match(bit) if not m: raise TemplateSyntaxError(self.error_msg) key = smart_str(m.group('key')) expr = parser.compile_filter(m.group('value')) self.options.append((key, expr)) self.as_var = bits[-1] self.nodelist_file = parser.parse(('empty', 'endthumbnail',)) if parser.next_token().contents == 'empty': self.nodelist_empty = parser.parse(('endthumbnail',)) parser.delete_first_token() else: self.nodelist_empty = NodeList() def _render(self, context): file_ = self.file_.resolve(context) geometry = self.geometry.resolve(context) options = {} for key, expr in self.options: noresolve = {'True': True, 'False': False, 'None': None} value = noresolve.get(unicode(expr), expr.resolve(context)) if key == 'options': options.update(value) else: options[key] = value if settings.THUMBNAIL_DUMMY: thumbnail = DummyImageFile(geometry) elif file_: thumbnail = default.backend.get_thumbnail( file_, geometry, **options ) else: return self.nodelist_empty.render(context) context.push() context[self.as_var] = thumbnail output = self.nodelist_file.render(context) context.pop() return output def __repr__(self): return "<ThumbnailNode>" def __iter__(self): for node in self.nodelist_file: yield node for node in self.nodelist_empty: yield node
def if_time(parser, token): bits = list(token.split_contents()) tag_name = bits[0] if tag_name.endswith('since'): future = False elif tag_name.endswith('until'): future = True if len(bits) != 4: raise TemplateSyntaxError("%r takes three arguments" % tag_name) end_tag = 'end' + tag_name nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag, )) parser.delete_first_token() else: nodelist_false = NodeList() parser.delete_first_token() try: time_int, time_unit = int(bits[3][:-1]), bits[3][-1] except ValueError: raise TemplateSyntaxError("Invalid argument '%s'" % bits[3]) if time_unit not in 'smhd': raise TemplateSyntaxError("Invalid argument '%s'" % bits[3]) return TimeNode(nodelist_true, nodelist_false, future=future, time=bits[1], operator=bits[2], elapsed=time_int, unit=time_unit)
def do_if_user_is_following(parser, token): """ same syntax as if/else/endif. if the current user is following the specified object (provided as the first argument) then the 'true' block is evaluated, otherwise the false or else block is evaluated. """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError, "'if_user_is_following' statement requires one argument [model object]" model_object_var = bits[1] nodelist_true = parser.parse(('else', 'endif')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endif',)) parser.delete_first_token() else: nodelist_false = NodeList() b = lambda context : Follow.objects.filter( user=Variable("request.user").resolve(context), object_id=Variable(model_object_var).resolve(context).pk, content_type=ContentType.objects.get_for_model(Variable(model_object_var).resolve(context)) ).exists() return BooleanNode(b, nodelist_true, nodelist_false)
def do_ifstartswith(parser, token): """ Outputs the contents of the block if the two arguments equal each other. Examples:: {% ifstartswith haystack needle %} ... {% endifstartswith %} {% ifstartswith haystack needle %} ... {% else %} ... {% endifstartswith %} """ bits = list(token.split_contents()) if len(bits) != 3: raise TemplateSyntaxError, "%r takes two arguments" % bits[0] end_tag = 'end' + bits[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag, )) parser.delete_first_token() else: nodelist_false = NodeList() val1 = parser.compile_filter(bits[1]) val2 = parser.compile_filter(bits[2]) return IfStartsWithNode(val1, val2, nodelist_true, nodelist_false)
def test_extends_node_repr(self): extends_node = ExtendsNode( nodelist=NodeList([]), parent_name=Node(), template_dirs=[], ) self.assertEqual(repr(extends_node), "<ExtendsNode: extends None>")
def timelimit(parser, token): """Used to guard section with a timeout: {% timelimit 0.05 %} <p>No timeout occurred</p> {% sleep 0.5 %} {% else %} <p>timeout!</p> {% endtimelimit %} @param parser: @param token: @return: """ bits = list(token.split_contents()) if len(bits) != 2: raise TemplateSyntaxError("No timeout specified") end_tag = 'end' + bits[0] nodelist_timeout = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_else = parser.parse((end_tag, )) parser.delete_first_token() else: nodelist_else = NodeList() return TimeoutNode(parser.compile_filter(bits[1]), nodelist_timeout, nodelist_else)
def render(self, context): nodelist = NodeList() sidebar_list = Sidebar.all().order("order").fetch(100) context.push() for sidebar in sidebar_list: context.push() context["sidebar"] = sidebar for node in self.nodelist_loop: nodelist.append(node.render(context)) context.pop() context.pop() return nodelist.render(context)
def requirejs_main(parser, token): """ Indicate that a page should be using RequireJS, by naming the JavaScript module to be used as the page's main entry point. The base template must have a `{% requirejs_main ... %}` tag before the `requirejs_main` variable is accessed anywhere in the template. The base template need not specify a value in its `{% requirejs_main %}` tag, allowing it to be extended by templates that may or may not use requirejs. In this case the `requirejs_main` template variable will have a value of `None` unless an extending template has a `{% requirejs_main "..." %}` with a value. """ bits = token.contents.split(None, 1) if len(bits) == 1: tag_name = bits[0] value = None else: tag_name, value = bits if getattr(parser, "__saw_requirejs_main", False): raise TemplateSyntaxError( "multiple '%s' tags not allowed (%s)" % tuple(bits)) parser.__saw_requirejs_main = True if value and (len(value) < 2 or value[0] not in '"\'' or value[0] != value[-1]): raise TemplateSyntaxError("bad '%s' argument: %s" % tuple(bits)) # use a block to allow extension template to set requirejs_main for base return loader_tags.BlockNode("__" + tag_name, NodeList([ RequireJSMainNode(tag_name, value and value[1:-1]) ]))
def ifstockmarket(parser, token): """ Check if stock market is running Usage: {% ifstockmarket active %} ... {% endifstockmarket %} """ try: tokensp = token.split_contents() status = tokensp[1] if status == 'active': status = True elif status == 'deactive': status = False else: raise template.TemplateSyntaxError("Tag 'ifstockmarket' requires at least 1 argument that should be active or deactive.") except ValueError: raise template.TemplateSyntaxError("Tag 'ifstockmarket' requires at least 1 argument.") nodelist_true = parser.parse(('else', 'endifstockmarket')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifstockmarket',)) parser.delete_first_token() else: nodelist_false = NodeList() return StatusCheckNode(status, nodelist_true, nodelist_false)
def ifusergroup(parser, token): """ Check to see if the currently logged in user belongs to one or more groups Requires the Django authentication contrib app and middleware. Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or {% ifusergroup Admins Clients Programmers Managers %} ... {% else %} ... {% endifusergroup %} """ try: tokensp = token.split_contents() groups = [] groups += tokensp[1:] except ValueError: raise template.TemplateSyntaxError( "Tag 'ifusergroup' requires at least 1 argument.") nodelist_true = parser.parse(('else', 'endifusergroup')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifusergroup', )) parser.delete_first_token() else: nodelist_false = NodeList() return GroupCheckNode(groups, nodelist_true, nodelist_false)
def ifusergroup(parser, token): """ Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and middleware. Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or {% ifusergroup Admins|Group1|Group2 %} ... {% endifusergroup %}, or {% ifusergroup Admins %} ... {% else %} ... {% endifusergroup %} """ try: tag, group = token.split_contents() except ValueError: raise template.TemplateSyntaxError( "Tag 'ifusergroup' requires 1 argument.") nodelist_true = parser.parse(('else', 'endifusergroup')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifusergroup', )) parser.delete_first_token() else: nodelist_false = NodeList() return GroupCheckNode(group, nodelist_true, nodelist_false)
def test_state_is_set_for_poll_box(self): user = User.objects.create(username='******') Vote.objects.create(poll=self.poll, user=user) box = Poll.box_class(self.poll, 'name', NodeList()) box.prepare(Context({'request': build_request(user=user)})) self.assert_equals( conf.USER_ALLREADY_VOTED, box.state)
def test_render_multiple_elements_with_remainder(self): models = [generate_random_model() for i in range(random.randint(5, 8))] nodelist = NodeList() nodelist.append(RenderNextNode("'full_page'")) nodelist.append(RenderNextNode("'show_request'")) nodelist.append(RenderNextNode("'full_page'")) nodelist.append(RenderRemainderNode("'full_page'")) node = RenderIterNode(Variable("list"), nodelist) rendered = node.render(Context({"list": models})) self.assertTrue(re.search(models[0].title, rendered)) self.assertFalse(re.search(models[1].title, rendered)) self.assertTrue(re.search(models[2].title, rendered)) for model in models[3:]: self.assertTrue(re.search(model.title, rendered))
def render(self, context, depth=0, values=False): nodelist = NodeList() if 'recurseloop' in context: parentloop = context['recurseloop'] else: parentloop = {} context.push() # On the first recursion pass, we have no values if not values: try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) # Create a recurseloop value in the context. We'll update counters on each iteration just below. loop_dict = context['recurseloop'] = {'parent': parentloop} loop_dict['depth'] = depth + 1 loop_dict['depth0'] = depth for i, item in enumerate(values): # Add the additional arguments to the context # They come in the form of {'name':(initial,increment)} # As for now only numbers are supported, but also strings can be multiplied for k,v in self.kwargs.iteritems(): context[k] = v[0] + v[1]*depth # Shortcuts for current loop iteration number. loop_dict['counter0'] = i loop_dict['counter'] = i+1 # Boolean values designating first and last times through loop. loop_dict['first'] = (i == 0) loop_dict['last'] = (i == len_values - 1) context[ self.loopvar ] = item for node in self.nodelist_first: nodelist.append( node.render(context) ) if len( getattr( item, self.children_name ) ): nodelist.append( self.render( context, depth+1, getattr( item, self.children_name ) ) ) for node in self.nodelist_second: nodelist.append( node.render(context) ) context.pop() return nodelist.render(context)
def __init__( self, nodelist_try: NodeList, nodelist_except: Optional[NodeList], catch_exceptions: Optional[List[str]] = None ): self.nodelist_try = nodelist_try self.nodelist_except = nodelist_except or NodeList() self.catch_exceptions = catch_exceptions
def test_state_is_set_for_poll_box_in_second_of_double_renders(self): settings.DOUBLE_RENDER = True user = User.objects.create(username='******') Vote.objects.create(poll=self.poll, user=user) box = Poll.box_class(self.poll, 'name', NodeList()) box.prepare(Context({'request': build_request(user=user), 'SECOND_RENDER': True})) self.assert_equals( conf.USER_ALLREADY_VOTED, box.state)
def test_render_position_with_invalid_target_returns_empty(self): target_ct = ContentType.objects.get_for_model(ContentType) invalid_id = ContentType.objects.aggregate(Max('id'))['id__max'] + 1 p = Position.objects.create(category=self.category, name='position-name', text='some text', target_ct=target_ct, target_id=invalid_id) self.assert_equals('', p.render(Context({}), NodeList(), ''))
def render(self, context): content_type_id = self.content_type_id.resolve(context) content_type = ContentType.objects.get_for_id(content_type_id) if hasattr(content_type.model_class(), 'get_absolute_url'): pk = self.pk.resolve(context) nodelist = NodeList() nodelist.append( LINK_FORMAT % reverse("object-detail", args=(content_type.pk, pk))) # nodelist.append(LINK_FORMAT % (content_type.pk, pk)) nodelist.append(self.inner_nodelist.render(context)) nodelist.append('</a>') return nodelist.render(context) else: return self.inner_nodelist.render(context)
def compile_nodelist(self): if register not in self.engine.template_builtins: self.engine.template_builtins += [register] ret = super().compile_nodelist() self.replace_nodes(ret) if self.filter_nodes: code_blocks = [] for block in ret: if not hasattr(block, 'name'): continue if block.name in self.filter_nodes: code_blocks.append(block) return NodeList(code_blocks) if self.one_node: return NodeList([self.find_node(ret, self.one_node)]) return ret
def do_ifloaded(parser, token): bits = token.split_contents()[1:] var = bits[0] nodelist_true = parser.parse(('else', 'endifloaded')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifloaded',)) parser.delete_first_token() else: nodelist_false = NodeList() return IfLoadedNode(var, nodelist_true, nodelist_false)
def render(self, context): nodelist = NodeList() if context.has_key('forloop'): parentloop = context['forloop'] else: parentloop = {} context.push() try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) if self.reversed: # From http://www.python.org/doc/current/tut/node11.html def reverse(data): for index in range(len(data) - 1, -1, -1): yield data[index] values = reverse(values) for i, item in enumerate(values): context['forloop'] = { # shortcuts for current loop iteration number 'counter0': i, 'counter': i + 1, # reverse counter iteration numbers 'revcounter': len_values - i, 'revcounter0': len_values - i - 1, # boolean values designating first and last times through loop 'first': (i == 0), 'last': (i == len_values - 1), 'parentloop': parentloop, } context[self.loopvar] = item for node in self.nodelist_loop: nodelist.append(node.render(context)) context.pop() return nodelist.render(context)
def ifusertutor(parser, token): nodelist_true = parser.parse(('else', 'endifusertutor')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifusertutor', )) parser.delete_first_token() else: nodelist_false = NodeList() return TutorCheckNode(nodelist_true, nodelist_false)
def __init__(self, shot=None, nodelist=None): if shot and shot.template_mixers: if nodelist: self.mixers = shot.template_mixers self.render = self.render_mixers self.inner_nodelist = nodelist else: # XXX when there's no inner nodes just monkey patch template # render method to reduce traversal time nodes = [MixerNode(mixer) for mixer in shot.template_mixers] self.render = NodeList(nodes).render
def parse(parser, token, end_tag): bits = token.split_contents()[1:2] var = TemplateIfParser(parser, bits).parse() nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag, )) parser.delete_first_token() else: nodelist_false = NodeList() return var, nodelist_true, nodelist_false
def media(parser, token): bits = token.split_contents() if bits[0] == 'media': if len(bits) != 2: raise TemplateSyntaxError("'media' takes one argument (type)") type = parser.compile_filter(bits[1]) else: if len(bits) != 1: raise TemplateSyntaxError("'%s' does not take arguments" % bits[0]) type = bits[0] nodelist = parser.parse(('end' + bits[0],)) parser.delete_first_token() node = MediaNode(type, nodelist) try: block = parser.__medias_block block.nodelist.append(node) return TextNode('') except AttributeError: pass try: if BLOCK_MEDIAS in parser.__loaded_blocks: return node parser.__loaded_blocks.append(BLOCK_MEDIAS) except AttributeError: parser.__loaded_blocks = [BLOCK_MEDIAS] nodelist = NodeList() nodelist.contains_nontext = True nodelist.append(parser.create_variable_node(parser.compile_filter('block.super'))) nodelist.append(node) block = BlockNode(BLOCK_MEDIAS, nodelist) parser.__medias_block = block return block
def render(self, context): nodelist = NodeList() if context.has_key('forloop'): parentloop = context['forloop'] else: parentloop = {} context.push() try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) if self.reversed: # From http://www.python.org/doc/current/tut/node11.html def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] values = reverse(values) for i, item in enumerate(values): context['forloop'] = { # shortcuts for current loop iteration number 'counter0': i, 'counter': i+1, # reverse counter iteration numbers 'revcounter': len_values - i, 'revcounter0': len_values - i - 1, # boolean values designating first and last times through loop 'first': (i == 0), 'last': (i == len_values - 1), 'parentloop': parentloop, } context[self.loopvar] = item for node in self.nodelist_loop: nodelist.append(node.render(context)) context.pop() return nodelist.render(context)
def render(self, context): actual_form = self.form_var.resolve(context) bindings = get_bindings(actual_form) # bindings.reverse() # bind in reverse order ... nodelist = NodeList() js_info = get_js_info(actual_form) # Add the script to activate this form nodelist.append( HtmlContent( """ <script> %s $(document).ready(function(){ // new ManagementForm(parentForm, childTemplate, initialForms); %s }); </script> """ % (js_info, "\n".join(bindings)) ) ) nodelist.append(HtmlContent("</div>")) return nodelist.render(context)
def __init__(self, parser, token): bits = token.split_contents() if len(bits) != 5 or bits[-2] != "as": raise TemplateSyntaxError(self.error_msg) self.file_ = parser.compile_filter(bits[1]) self.preset = parser.compile_filter(bits[2]) self.as_var = bits[-1] self.nodelist_file = parser.parse(("empty", "endthumbnail")) if parser.next_token().contents == "empty": self.nodelist_empty = parser.parse(("endthumbnail",)) parser.delete_first_token() else: self.nodelist_empty = NodeList()
def do_ifin(parser, token, negate): bits = list(token.split_contents()) if len(bits) != 3: raise TemplateSyntaxError, "%r takes two arguments" % bits[0] end_tag = 'end' + bits[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag, )) parser.delete_first_token() else: nodelist_false = NodeList() return IfInNode(bits[1], bits[2], nodelist_true, nodelist_false, negate)
def render(self, context): content_type_id = self.content_type_id.resolve(context) content_type = ContentType.objects.get_for_id(content_type_id) if hasattr(content_type.model_class(), 'get_absolute_url'): pk = self.pk.resolve(context) nodelist = NodeList() nodelist.append(LINK_FORMAT % reverse("object-detail", args=(content_type.pk, pk))) # nodelist.append(LINK_FORMAT % (content_type.pk, pk)) nodelist.append(self.inner_nodelist.render(context)) nodelist.append('</a>') return nodelist.render(context) else: return self.inner_nodelist.render(context)
class IncludeNode(Node): def __init__(self, nodelist, path): self.template = get_template(path) self.nodelist, self.path = NodeList(nodelist), path def __repr__(self): return "<Include Node: %s Contents: %r>" % (self.path, self.nodelist) def render(self, context): parent_blocks = dict([(n.name, n) for n in self.template.nodelist.get_nodes_by_type(PartNode)]) for part_node in self.nodelist.get_nodes_by_type(PartNode): parent_block = parent_blocks[part_node.name] parent_block.nodelist = part_node.nodelist return self.template.render(context)
def forcomment(context, nodelist, filediff, review=None): """ Loops over a list of comments beloning to a filediff. This will populate a special ``comment`` variable for use in the content. This is of the type :model:`reviews.Comment`. """ new_nodelist = NodeList() context.push() if not review: comments = filediff.comments.all() else: comments = filediff.comments.filter(review=review) for comment in comments: context['comment'] = comment for node in nodelist: new_nodelist.append(node.render(context)) context.pop() return new_nodelist.render(context)
def item_description(self, item): if not core_settings.RSS_DESCRIPTION_BOX_TYPE: return item.publishable.description p = item.publishable box = p.box_class(p, core_settings.RSS_DESCRIPTION_BOX_TYPE, NodeList()) try: desc = box.render(self.box_context) except TemplateDoesNotExist: desc = None if not desc: desc = item.publishable.description return desc
def from_string(cls, template_soup, origin=''): result = TemplateComponentBucket() within = None node_bucket = NodeList() for m in Lexer(template_soup, origin).tokenize(): attributes = m.split_contents() if not attributes: continue if attributes[0] in cls.BLOCKTAGS: prop = cls._parse_parameters(attributes) within = attributes[0] node_bucket = NodeList() elif attributes[0] in cls.ENDBLOCKTAGS: prop['blocktag'] = within within = None rendered_inner = Parser(node_bucket).parse().render(TEMPLATECOMPONENTS_CONTEXT) result.append(TemplateComponentBlock(rendered_inner, origin=origin, **prop)) elif within: node_bucket.append(m) return result
def callback(tagname, label=None): if label is None: nodelist = parser.parse(('endtitle',)) parser.delete_first_token() return TitleNode(tagname, nodelist) else: # WARNING: Undocumented festures of Django are used here. from django.template import FilterExpression, NodeList, Parser, VariableNode from django.template.loader_tags import BlockNode nodelist = NodeList() nodelist.append(TitleComponentNode(tagname, label)) nodelist.append(VariableNode(FilterExpression('block.super', Parser('')))) nodelist2 = NodeList() nodelist2.append(BlockNode('title', nodelist)) return NodeListNode(nodelist2)
def callback(tagname, label=None, url=None, urlname=None): if label is None and url is None and urlname is None: nodelist = parser.parse(('endpath',)) parser.delete_first_token() return PathNode(tagname, nodelist) elif label is not None and (url is not None or urlname is not None): # WARNING: Undocumented festures of Django are used here. from django.template import FilterExpression, NodeList, Parser, VariableNode from django.template.loader_tags import BlockNode nodelist = NodeList() nodelist.append(VariableNode(FilterExpression('block.super', Parser('')))) nodelist.append(PathComponentNode(tagname, label, url, urlname)) nodelist2 = NodeList() nodelist2.append(BlockNode('path', nodelist)) return NodeListNode(nodelist2) else: raise template.TemplateSyntaxError('%s tag syntax error' % tagname)
class ThumbnailNode(thumbnail.ThumbnailNodeBase): child_nodelists = ("nodelist_file", "nodelist_empty") error_msg = "Syntax error. Expected: ``thumbnail source preset as var``" preset_error = "Preset %s not found." def __init__(self, parser, token): bits = token.split_contents() if len(bits) != 5 or bits[-2] != "as": raise TemplateSyntaxError(self.error_msg) self.file_ = parser.compile_filter(bits[1]) self.preset = parser.compile_filter(bits[2]) self.as_var = bits[-1] self.nodelist_file = parser.parse(("empty", "endthumbnail")) if parser.next_token().contents == "empty": self.nodelist_empty = parser.parse(("endthumbnail",)) parser.delete_first_token() else: self.nodelist_empty = NodeList() def _render(self, context): file_ = self.file_.resolve(context) preset_name = self.preset.resolve(context) preset = Preset.objects.get(name=preset_name) if settings.THUMBNAIL_DUMMY: thumbnail = DummyImageFile(preset.geometry) elif file_: thumbnail = default.backend.get_thumbnail(file_, preset.geometry, **preset.get_options()) else: return self.nodelist_empty.render(context) context.push() context[self.as_var] = thumbnail output = self.nodelist_file.render(context) context.pop() return output def __repr__(self): return "<ImageCacheNode>" def __iter__(self): for node in self.nodelist_file: yield node for node in self.nodelist_empty: yield node