Python 如何在 Django 模板中使用 break 和 continue?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4921027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use break and continue in Django templates?
提问by GoldenBird
I want to put break and continue in my code, but it doesn't work in Django template. How can I use continue and break using Django template for loop. Here is an example:
我想在我的代码中放置 break 和 continue,但它在 Django 模板中不起作用。如何使用 Django 模板循环使用 continue 和 break。下面是一个例子:
{% for i in i_range %}
{% for frequency in patient_meds.frequency %}
{% ifequal frequency i %}
<td class="nopad"><input type="checkbox" name="frequency-1" value="{{ i }}" checked/> {{ i }} AM</td>
{{ forloop.parentloop|continue }} ////// It doesn't work
{ continue } ////// It also doesn't work
{% endifequal %}
{% endfor%}
<td class="nopad"><input type="checkbox" name="frequency-1" value="{{ i }}"/> {{ i }} AM</td>
{% endfor %}
采纳答案by Gintautas Miliauskas
For-loops in Django templates are different from plain Python for-loops, so continueand breakwill not work in them. See for yourself in the Django docs, there are no breakor continuetemplate tags. Given the overall position of Keep-It-Simple-Stupid in Django template syntax, you will probably have to find another way to accomplish what you need.
Django 模板中的 for 循环与普通的 Python for 循环不同,因此continue并且break在它们中不起作用。在 Django文档中亲自查看,没有break或continue模板标签。考虑到 Keep-It-Simple-Stupid 在 Django 模板语法中的总体地位,您可能必须找到另一种方法来完成您所需要的。
回答by Jasim Muhammed
Django doesn't support it naturally.
Django 自然不支持它。
You can implement forloop|continue and forloop|break with custom filters.
您可以使用自定义过滤器实现 forloop|continue 和 forloop|break。
回答by S?awomir Lenart
For most of cases there is no need for custom templatetags, it's easy:
大多数情况下不需要自定义模板标签,这很简单:
continue:
继续:
{% for each in iterable %}
{% if conditions_for_continue %}
<!-- continue -->
{% else %}
... code ..
{% endif %}
{% endfor %}
breakuse the same idea, but with the wider scope:
break使用相同的想法,但范围更广:
{% set stop_loop="" %}
{% for each in iterable %}
{% if stop_loop %}{% else %}
... code ..
under some condition {% set stop_loop="true" %}
... code ..
{% endif %}
{% endfor %}
if you accept iterating more than needed.
如果您接受超出需要的迭代次数。

