【发布时间】:2013-04-23 15:40:52
【问题描述】:
在 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>
【问题讨论】:
-
mipadi 对“查找项目列表是否为空”的问题的回答是正确的,但 OP 错误地使用了
for..else。 Django 模板for..empty-empty表示for循环没有任何项目。而 Pythonfor..else-else表示 for 循环没有退出(中断)。 -
另外,您不应该将列表命名为“列表”!在
list = []之后,您将无法拨打list()
标签: python django django-templates