8

How would I do the following in jinja2:

while apples < oranges:
    # some work here.

According to http://jinja.pocoo.org/docs/dev/extensions/#loop-controls, and by the error I am getting, Jinja2 does not support while loops.

The question is I want to continuously do some work as long as the value of apples is less than that of oranges

Thanks for any help.

Also something equivalent to while True: is good also.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
kasavbere
  • 5,873
  • 14
  • 49
  • 72
  • 1
    I didn't even know jinja2 had variables that could change values in a way that would make that make sense. Why are you putting business logic in a template anyway? – Wooble Dec 15 '12 at 23:08

1 Answers1

7

To loop in Jina2 you have to use : for. To end the loop in the for block you can use break. See : http://jinja.pocoo.org/docs/extensions/#loop-controls.

jinja_env = Environment(extensions=['jinja2.ext.loopcontrols'])

An "endless" loop you can create with:

{% for _ in range(1, large_number) %}

   {% if loop.index > stop_at %}{% break %}{% endif %} 

{% endfor %}
voscausa
  • 11,253
  • 2
  • 39
  • 67
  • @vocausa seem to be you can't use break anymore, and I'm actually puzzled how to write something like this without break?? – holms Apr 28 '15 at 22:12
  • using something like `{% for user in users if not user.hidden %}` from the [docs](http://jinja.pocoo.org/docs/dev/templates/) – muttonchops Feb 15 '16 at 13:29
  • @muttonchops i don't understand this statement in my case it's useless. I need to go through all i team and if found break a loop, if not continue looping. I don't need any exclusions.. – holms Mar 10 '18 at 00:22