Dashboard > Pylons Projects > Home > Cycle API
  Pylons Projects Log In | Sign Up   View a printable version of the current page.  
  Cycle API
Added by Mike Orr, last edited by Mike Orr on Jun 27, 2008
Labels: 
(None)

This is a proposed API for a Cycle object in WebHelpers.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Cycle(object):
    """This is like iterating a circular list: when you reach the end, go back to the beginning and
    continue forever.  But this class also handles a linear progression of cycle -> sub-cycle ->
    sub-sub-cycle, to any depth; e.g., for one-to-many relationships.

    One-level usage is like this:

    <%   my_cycle = Cycle(["even", "odd"])   %>
    % for r in c.records:
        <tr class="${my_cycle.next()}">
        ...
    % endfor


    Multi-level could be used to display a one-to-many relationship, where the child objects
    are listed indented after their parent.  The parent here alternates between "white" and "blue"
    classes for its table rows, while the child alternates between "evenchild" and "oddchild".
    The child cycle is reset to the beginning for each group of child records.

    <%   my_cycle = Cycle(["white", "blue"], ["evenchild", "oddchild"])   %>
    <table>
    % for parent_record in c.records:
        <tr class="${my_cycle.next()}">
        ...
        <%  my_cycle.cycle.reset()  %>
        <table>
        % for child_record in parent_record.children:
            <tr class="${my_cycle.cycle.next()}">
            ...
            </tr>
        % endfor
        </table>
        </tr>
    % endfor
    </table>
    """

    def __init__(self, choices, *descendant_choices):
        self.choices = list(choices)
        self.index = 0   # Index of next choice to produce.
        self.cycle = None        
        if descendant_choices:
            self.cycle = Cycle(*descendant_choices)

    def next(self):
        if self.index >= len(self.choices):
            self.index = 0
        element = self.choices[self.index]
        self.index += 1
        return element
        # Cycle is endless, no need for StopIteration.

    def reset(self):
        self.index = 0

Site running on a free Atlassian Confluence Open Source Project License granted to Pylons. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.3.3 Build:#645 Feb 13, 2007) - Bug/feature request - Contact Administrators