2013-04-29 100 views
11

在Django模板语言中,有没有使用带有for循环的else子句?我依赖我可以在for循环之前使用if检查,但这会重复。Django模板语言:在其他语言中使用for循环

蟒蛇换别的

list = [] 

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

Django的模板,否则(我猜测)

<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> 
+1

mipadi的答案是正确的问题“找到一个项目列表是否为空”,但OP是错误地使用'for..else'。 Django Template'for..empty' - 'empty'表示for循环没有任何项目。 while Python'for..else' - 'else'表示for循环没有退出(break)。 – Andrew 2016-10-06 07:20:49

回答

18

使用for...empty,这基本上是Django的当量(以empty替换else关键字)。

+0

正如Andrew所说(在对此问题的评论中),“for..empty”是OP所要求的,但for..else在Python中完全不同。 – 2017-09-01 15:09:20