19

在 Django 模板语言中,是否可以使用带有 for 循环的 else 子句?我相信我可以在 for 循环之前使用 if 检查,但这会重复。

python for-else

list = []

for i in list:
    print i
else:
    print 'list is empty'

Django 模板 for-else(我的猜测)

<h1>{{ game.title}}</h1>

<table>
    <tr> 

{% for platform in game.platform_set.all %}       
    <td>{{ platform.system }} -- ${{ platform.price}}</td> 
{% else %}
    <td>No Platforms</td>
{% endfor %}

    </tr>
</table>

<a href="{% url 'video_games:profile' game.id %}"></a> 
4

2 回答 2

32

使用for...empty,它基本上是 Django 等价物(将else关键字替换为empty)。

于 2013-04-29T20:33:44.150 回答
0

我知道这是一个非常古老的帖子。添加答案以供将来参考。没有明确的方法可以实现for..else,但我们可以执行以下操作。

{% for x in some_list %}
    ... awesome html and more here
    
    {% if forloop.last %}
        ... executes only if this is the last time through the loop
    {% endif %}

{% endfor %}

希望这可以帮助。更多阅读在这里

于 2021-11-30T21:39:11.073 回答