How can I use break and continue in Django templates?


Question

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:

{% 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 %}
1
18
9/5/2015 5:20:40 AM

Accepted Answer

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.

28
2/11/2011 11:38:33 PM

Django doesn't support it naturally.

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon