在Django模板语言中,可以使用带有for循环的else子句吗?我依赖于我可以在for循环之前使用if检查,但这会重复。
python for-else
list = []
for i in list:
print i
else:
print 'list is empty'-else的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> 发布于 2013-04-30 04:33:44
使用for...empty,它基本上等同于Django (用empty替换else关键字)。
发布于 2021-11-30 21:39:11
我知道这是一个非常古老的帖子。添加答案以供将来参考。没有明确的方法来实现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 %}希望这能有所帮助。更多阅读here
https://stackoverflow.com/questions/16287695
复制相似问题