Ticket #5908: resetcycle.diff

File resetcycle.diff, 2.4 KB (added by Ville Säävuori, 17 years ago)

First stab at resetcycle tag

  • django/template/defaulttags.py

     
    4141    def __init__(self, cyclevars, variable_name=None):
    4242        self.cycle_iter = itertools_cycle(cyclevars)
    4343        self.variable_name = variable_name
     44        self.cyclevars = cyclevars
    4445
    45     def render(self, context):
     46    def render(self, context):       
     47        if context.has_key('resetcycle'):
     48            if context['resetcycle'] != None:
     49                reset_name = context['resetcycle'][0]
     50            else:
     51                reset_name = None
     52           
     53            if self.variable_name == reset_name:
     54                self.cycle_iter = itertools_cycle(self.cyclevars)
     55                for d in context.dicts:
     56                    if 'resetcycle' in d:
     57                        del(d['resetcycle'])
    4658        value = self.cycle_iter.next()
    4759        value = Variable(value).resolve(context)
    4860        if self.variable_name:
    4961            context[self.variable_name] = value
    5062        return value
    5163
     64class ResetCycleNode(Node):
     65    def __init__(self, variable_name=None):
     66        self.variable_name = variable_name
     67
     68    def render(self, context):
     69        context['resetcycle'] = self.variable_name
     70        return ''
     71
    5272class DebugNode(Node):
    5373    def render(self, context):
    5474        from pprint import pformat
     
    498518    return node
    499519cycle = register.tag(cycle)
    500520
     521def resetcycle(parser, token):
     522    """
     523    Resets cycle tag.
     524   
     525    If argument is given, resets the cycle named argument, else resets last
     526    non-named argument.
     527    """
     528    args = token.split_contents()
     529   
     530    if len(args) > 2:
     531        raise TemplateSyntaxError("'resetcycle' tag accepts maximum of one argument.")
     532   
     533    if len(args) == 2:
     534        # {% resetcycle foo %} case.
     535        name = args[1]
     536        if not hasattr(parser, '_namedCycleNodes'):
     537            raise TemplateSyntaxError("No named cycles in template."
     538                                      " '%s' is not defined" % name)
     539        if not name in parser._namedCycleNodes:
     540            raise TemplateSyntaxError("Named cycle '%s' does not exist" % name)
     541        return ResetCycleNode(args[1:])
     542    return ResetCycleNode()
     543resetcycle = register.tag(resetcycle)
     544
    501545def debug(parser, token):
    502546    """
    503547    Outputs a whole load of debugging information, including the current
Back to Top