How can I use break and continue in Django templates?

前端 未结 3 1611
渐次进展
渐次进展 2020-12-17 09:44

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:

相关标签:
3条回答
  • 2020-12-17 10:08

    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.

    0 讨论(0)
  • 2020-12-17 10:17

    For-loops in Django templates are different from plain Python for-loops, so continue and break will not work in them. See for yourself in the Django docs, there are no break or continue template 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.

    0 讨论(0)
  • 2020-12-17 10:28

    Django doesn't support it naturally.

    You can implement forloop|continue and forloop|break with custom filters.

    http://djangosnippets.org/snippets/2093/

    0 讨论(0)
提交回复
热议问题