[Django]-How can I use break and continue in Django templates?

37๐Ÿ‘

โœ…

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.

40๐Ÿ‘

Django doesnโ€™t support it naturally.

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

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

๐Ÿ‘คJasim Muhammed

16๐Ÿ‘

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 %}

This is Jinja template, which you can easily use within Django b/c Jinja is built in.

You can use even both template backends in the same project (Jinja and Django template).

2๐Ÿ‘

If you want a continue/break after certain conditions, I use the following Simple Tag as follows with "Vanilla" Django 3.2.5:

@register.simple_tag
def define(val=None):
  return val

Then you can use it as any variable in the template

{% define True as continue %}
      
{% 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.

๐Ÿ‘คRudolf Jacobs

Leave a comment