Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 Template - for loop

didn't find another post which has the similar problem, I'm trying to generate some checkboxes with flask and wtforms, at the moment I've got this piece of code:

<div class="control-group">
    <p><strong>Check the enabled BRI Ports</strong></p>
    <label class="checkbox inline">
        {{ form.bri1(value=1) }} {{ form.bri1.label }}
    </label>
    <label class="checkbox inline">
        {{ form.bri2(value=1) }} {{ form.bri2.label }}
    </label>
    <label class="checkbox inline">
        {{ form.bri3(value=1) }} {{ form.bri3.label }}
    </label>
    <label class="checkbox inline">
        {{ form.bri4(value=1) }} {{ form.bri4.label }}
    </label>
</div>

This works so far, but now I try to do this with a simple for-loop like:

<div class="control-group">
    <p><strong>Check the enabled BRI Ports</strong></p>
    {% for n in range(1,6) %}
    <label class="checkbox inline">
        {{ form.brin.label }}
    {% endfor %}
</div>

I tried with (), {} and {{}} ... is this even possible?

like image 965
Kilrathy Avatar asked May 22 '13 08:05

Kilrathy


People also ask

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.

How do you iterate through a list in Jinja?

To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop. to create the parent_list list of dicts. in our Jinja2 template to render the parent_list items in a for loop.


1 Answers

Try:

<div class="control-group">
    <p><strong>Check the enabled BRI Ports</strong></p>
    {% for name, field in form._fields.items() %}
        {% if name != 'csrf_token' %}
            <label class="checkbox inline">
                {{ field(value=1) }} {{ field.label }}
            </label>
        {% endif %}
    {% endfor %}
</div>

There you can set sorting instead form._fields.items() or condition instead {% if name != 'csrf_token' %}. Or:

<div class="control-group">
    <p><strong>Check the enabled BRI Ports</strong></p>
    {% for n in range(1,6) %}
        {% if form['bri' + n|string] %}
            <label class="checkbox inline">
                {{ form['bri' + n|string](value=1) }} {{ form['bri' + n|string].label }}
            </label>
        {% endif %}
    {% endfor %}
</div>

There you can also use n.__str__() instead filter n|string.

like image 94
tbicr Avatar answered Sep 23 '22 11:09

tbicr