Ticket #6398: add_default_to_for.2.diff

File add_default_to_for.2.diff, 4.9 KB (added by jezdez, 7 years ago)

Third implementation, including documentation and tests, fixing some issues, thanks SmileyChris!

  • django/template/defaulttags.py

     
    8484        return u''
    8585
    8686class ForNode(Node):
    87     def __init__(self, loopvars, sequence, is_reversed, nodelist_loop):
     87    def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_default):
    8888        self.loopvars, self.sequence = loopvars, sequence
    8989        self.is_reversed = is_reversed
    90         self.nodelist_loop = nodelist_loop
     90        self.nodelist_loop, self.nodelist_default = nodelist_loop, nodelist_default
    9191
    9292    def __repr__(self):
    9393        reversed_text = self.is_reversed and ' reversed' or ''
     
    9898    def __iter__(self):
    9999        for node in self.nodelist_loop:
    100100            yield node
     101        for node in self.nodelist_default:
     102            yield node
    101103
    102104    def get_nodes_by_type(self, nodetype):
    103105        nodes = []
    104106        if isinstance(self, nodetype):
    105107            nodes.append(self)
    106108        nodes.extend(self.nodelist_loop.get_nodes_by_type(nodetype))
     109        nodes.extend(self.nodelist_default.get_nodes_by_type(nodetype))
    107110        return nodes
    108111
    109112    def render(self, context):
     
    122125        if not hasattr(values, '__len__'):
    123126            values = list(values)
    124127        len_values = len(values)
     128        if len_values < 1:
     129            return self.nodelist_default.render(context)
    125130        if self.is_reversed:
    126131            values = reversed(values)
    127132        unpack = len(self.loopvars) > 1
     
    594599            {{ key }}: {{ value }}
    595600        {% endfor %}
    596601
     602    As you can see, the ``for`` tag can take an option ``{% default %}`` clause
     603    that will be displayed if the given array is empty or could not be found::
     604
     605        <ul>
     606        {% for athlete in athlete_list %}
     607            <li>{{ athlete.name }}</li>
     608        {% default %}
     609            <li>Sorry, no athlete in this list!</li>
     610        {% endfor %}
     611        <ul>
     612
    597613    The for loop sets a number of variables available within the loop:
    598614
    599615        ==========================  ================================================
     
    630646                                      " %s" % token.contents)
    631647
    632648    sequence = parser.compile_filter(bits[in_index+1])
    633     nodelist_loop = parser.parse(('endfor',))
    634     parser.delete_first_token()
    635     return ForNode(loopvars, sequence, is_reversed, nodelist_loop)
     649    nodelist_loop = parser.parse(('default', 'endfor',))
     650    token = parser.next_token()
     651    if token.contents == 'default':
     652        nodelist_default = parser.parse(('endfor',))
     653        parser.delete_first_token()
     654    else:
     655        nodelist_default = NodeList()
     656    return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_default)
    636657do_for = register.tag("for", do_for)
    637658
    638659def do_ifequal(parser, token, negate):
  • tests/regressiontests/templates/tests.py

     
    457457            'for-tag-unpack11': ("{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, ("one:1,/two:2,/", "one:1,INVALID/two:2,INVALID/")),
    458458            'for-tag-unpack12': ("{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}", {"items": (('one', 1, 'carrot'), ('two', 2))}, ("one:1,carrot/two:2,/", "one:1,carrot/two:2,INVALID/")),
    459459            'for-tag-unpack13': ("{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}", {"items": (('one', 1, 'carrot'), ('two', 2, 'cheese'))}, ("one:1,carrot/two:2,cheese/", "one:1,carrot/two:2,cheese/")),
     460            'for-tag-default01': ("{% for val in values %}{{ val }}{% default %}values array empty{% endfor %}", {"values": []}, "values array empty"),
     461            'for-tag-default02': ("{% for val in values %}{{ val }}{% default %}values array not found{% endfor %}", {}, "values array not found"),
    460462
    461463            ### IF TAG ################################################################
    462464            'if-tag01': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": True}, "yes"),
  • docs/templates.txt

     
    717717        {{ key }}: {{ value }}
    718718    {% endfor %}
    719719
     720**New in Django development version**
     721The ``for`` tag can take an optional ``{% default %}`` clause that will be
     722displayed if the given array is empty or could not be found::
     723
     724    <ul>
     725    {% for athlete in athlete_list %}
     726        <li>{{ athlete.name }}</li>
     727    {% default %}
     728        <li>Sorry, no athlete in this list!</li>
     729    {% endfor %}
     730    <ul>
     731
    720732The for loop sets a number of variables available within the loop:
    721733
    722734    ==========================  ================================================
Back to Top