Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use break and continue in Django templates?

Tags:

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 %} 
like image 859
GoldenBird Avatar asked Feb 07 '11 11:02

GoldenBird


People also ask

How do I stop a loop in Django?

There is no break in Django template system but you can achieve an statement like break with bellow architecture. (Loop will go iteration but u don't do anything.) 1- Use with to define a variable to determine current status, 2- Use a template custom tag to change statement to negate current status.

Do Django templates have multiple extends?

Yes you can extend different or same templates.

Which option does Django templates accept?

DjangoTemplates engines accept the following OPTIONS : 'autoescape' : a boolean that controls whether HTML autoescaping is enabled. It defaults to True . Only set it to False if you're rendering non-HTML templates!

What does {% include %} do in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.


2 Answers

Django doesn't support it naturally.

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

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

like image 67
Jasim Muhammed Avatar answered Nov 07 '22 12:11

Jasim Muhammed


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.

like image 31
Gintautas Miliauskas Avatar answered Nov 07 '22 13:11

Gintautas Miliauskas