How can I check the size of a collection within a Django template?

前端 未结 7 1491
南旧
南旧 2020-12-12 21:31

I have a list in my Django template. I want to do something only if the size of the list is greater than zero.

I have tried myList|length and m

相关标签:
7条回答
  • 2020-12-12 21:49

    A list is considered to be False if it has no elements, so you can do something like this:

    {% if mylist %}
        <p>I have a list!</p>
    {% else %}
        <p>I don't have a list!</p>
    {% endif %}
    
    0 讨论(0)
  • 2020-12-12 21:49

    I need the collection length to decide whether I should render table <thead></thead>

    but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop afterward.

    I got to use {% if forloop.first %} {% endif %} to overcome:

    <table>
        {% for record in service_list %}
            {% if forloop.first %}
                <thead>
                <tr>
                    <th>日期</th>
                </tr>
                </thead>
            {% endif %}
            <tbody>
            <tr>
                <td>{{ record.date }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    
    0 讨论(0)
  • 2020-12-12 21:56

    If you're using a recent Django, changelist 9530 introduced an {% empty %} block, allowing you to write

    {% for athlete in athlete_list %}
      ...
    {% empty %}
      No athletes
    {% endfor %}
    

    Useful when the something that you want to do involves special treatment for lists that might be empty.

    0 讨论(0)
  • 2020-12-12 21:57

    You can try with:

    {% if theList.object_list.count > 0 %}
        blah, blah...
    {% else %}
        blah, blah....
    {% endif %} 
    
    0 讨论(0)
  • 2020-12-12 21:58

    See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:

    {% if athlete_list %}
        Number of athletes: {{ athlete_list|length }}
    {% else %}
        No athletes.
    {% endif %}
    
    0 讨论(0)
  • 2020-12-12 21:58

    Collection.count no bracket

    {% if request.user.is_authenticated %}
    {{wishlists.count}}
    {% else %}0{% endif %}
    
    0 讨论(0)
提交回复
热议问题