Behavior of the for-else construct

Peter J. Holzer hjp-python at hjp.at
Fri Mar 4 18:11:50 EST 2022


On 2022-03-04 14:04:48 -0600, Om Joshi wrote:
> I'm not sure if anyone has mentioned it on this thread, but with
> respect to your comment about adding either on.empty or a decorator,
> the Django template syntax uses
> 
> {% for x in iterator %}
>  <h2>{{ x }}</h2>
> {% empty %}
>  <h2>Empty</h2>
> {% endfor %}
> 
> and this seems to work quite well and be incredibly intuitive, at
> least for Django html templates.

OTOH it is frequently not what you want.

Take this example from the Django docs:

    <ul>
    {% for athlete in athlete_list %}
        <li>{{ athlete.name }}</li>
    {% empty %}
        <li>Sorry, no athletes in this list.</li>
    {% endfor %}
    </ul>

If athlete_list is empty, it will produce:

    <ul>
        <li>Sorry, no athletes in this list.</li>
    </ul>

which is awful typography. You don't want a list with a single item, you
want that text *instead of* the list.

So you would have to write

    {% if athlete_list %}
        <ul>
        {% for athlete in athlete_list %}
            <li>{{ athlete.name }}</li>
        {% empty %}
        </ul>
    {% else %}
        <div class="whatever">
            Sorry, no athletes in this list.
        </div>
    {%endif %}

anyway.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20220305/edadff6d/attachment.sig>


More information about the Python-list mailing list