Login

While loop template tag

Author:
gsakkis
Posted:
July 5, 2010
Language:
Python
Version:
1.2
Score:
1 (after 3 ratings)

The missing while template tag. Built on top of http://djangosnippets.org/snippets/2093/, it also supports break and continue out of the box.

 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from django import template

# see http://djangosnippets.org/snippets/2093/
from looptags import Loop

register = template.Library()

@register.tag('while')
class WhileNode(template.Node):
    '''Loops over a block as long as a boolean expression is "true".

    For example, to pop each athlete from a list of athletes ``athlete_list``::

        <ul>
        {% while athlete_list %}
            <li>{{ athlete_list.pop.name }}</li>
        {% endwhile %}
        </ul>

    The while loop sets a number of variables available within the loop:

        ==========================  ================================================
        Variable                    Description
        ==========================  ================================================
        ``whileloop.counter``       The current iteration of the loop (1-indexed)
        ``whileloop.counter0``      The current iteration of the loop (0-indexed)
                                    loop (0-indexed)
        ``whileloop.first``         True if this is the first time through the loop
        ``whileloop.parentloop``    For nested loops, this is the loop "above" the
                                    current one
        ==========================  ================================================

    You can also ``continue`` or ``break`` from the loop by using the respective
    filters on the ``whileloop`` variable::

        <ul>
        {% while athlete_list %}
            {% with athlete_list.pop.name as athlete %}
                {% if athlete == 'Woods' %}
                    {{ whileloop|continue }}
                {% endif %}
                <li>{{ athlete }}</li>
                {% if athlete == 'Pele' %}
                    {{ whileloop|break }}
                {% endif %}
            {% endwith %}
        {% endwhile %}
        </ul>
    '''

    child_nodelists = ('nodelist_loop',)

    def __init__(self, parser, token):
        bits = token.split_contents()[1:]
        self.var = template.defaulttags.TemplateIfParser(parser, bits).parse()
        self.nodelist_loop = parser.parse(('endwhile',))
        parser.delete_first_token()

    def __rer__(self):
        return "<While node>"

    def __iter__(self):
        return self.nodelist_loop

    def render(self, context):
        loop = Loop('whileloop', context, self.nodelist_loop)
        eval_var = self.var.eval
        while True:
            try:
                if not eval_var(context):
                    break
            except template.VariableDoesNotExist:
                break
            if loop.next() is loop.BREAK:
                break
        return loop.render(close=True)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.