[英]How can I use break and continue in Django templates?
I want to put break and continue in my code, but it doesn't work in Django template.我想在我的代码中放置 break 和 continue,但它在 Django 模板中不起作用。 How can I use continue and break using Django template for loop.
如何使用 Django 模板循环使用 continue 和 break。 Here is an example:
下面是一个例子:
{% 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 %}
Django doesn't support it naturally. Django自然不支持它。
You can implement forloop|continue and forloop|break with custom filters. 您可以使用自定义过滤器实现forloop | continue和forloop | break。
http://djangosnippets.org/snippets/2093/ http://djangosnippets.org/snippets/2093/
For-loops in Django templates are different from plain Python for-loops, so continue
and break
will not work in them. Django模板中的for循环不同于普通的Python for循环,因此
continue
和break
在它们中不起作用。 See for yourself in the Django docs , there are no break
or continue
template tags. 在Django 文档中亲自查看,没有
break
或continue
模板标签。 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模板语法中Keep-It-Simple-Stupid的总体位置,您可能必须寻找另一种方式来完成所需的工作。
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 %}
break use the same idea, but with the wider scope: 打破使用相同的想法,但与更广泛的范围:
{% 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. 如果您接受超出需要的迭代。
If you want a continue/break after certain conditions, I use the following Simple Tag as follows with "Vanilla" Django 3.2.5:如果您想在某些条件后继续/中断,我将使用以下简单标记,如下所示与“Vanilla”Django 3.2.5:
@register.simple_tag def define(val=None): return val @register.simple_tag defdefine(val=None):返回val
Then you can use it as any variable in the template然后您可以将其用作模板中的任何变量
{% define True as continue %} {% 定义 True 为继续 %}
{% for u in queryset %} {% for u in queryset %}
{% if continue %} {% 如果继续 %}
{% if u.status.description == 'Passed' %}
<td>Passed</td>
{% define False as continue %}
{% endif %}
{% endif %} {% 万一 %}
{% endfor %} {% 结束为 %}
Extremely useful for any type of variable you want to re-use on template without using "with" statements.对于要在模板上重用而不使用“with”语句的任何类型的变量都非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.