loop for Jinj2 flask

Asked

Viewed 66 times

0

I have a loop 'for" in the template only I want it to show a certain amount result.

{% for form in form %}
    <tr>
       <td><img src="../static/img/arrow-gray.png" alt="">
       <font color="#e3068f"> IGLO{{ form.callsign }}</font></td>
       <td>{{ form.username  }} <b>{{ form.sobrename }}</b></td>
       <td>{{ form.last_seen }}</td>
    </tr>
{% endfor %}

inserir a descrição da imagem aqui

if I use {{ for form in form }} it shows the result

inserir a descrição da imagem aqui

Now if I put "{{ for form in range(2) }}" I only want to show 2 result, it shows nothing.

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

1 answer

1


There are two basic errors in its application. The first one is in relation to the nomenclature of the variables. In the excerpt

{% for form in form %}

you are naming the variable that goes through the list form also of form. In this case, the correct way is to give a different name from the list for the iterator. An example would be:

{% for f in form %}

The other error is that you want to limit to two records only. In this case, you can actually iterate over the function range(), but now the list should be indexed on the entire index you are iterating.

{% for f in form %}
    <tr>
       <td><img src="../static/img/arrow-gray.png" alt="">
       <font color="#e3068f"> IGLO{{ f[i].callsign }}</font></td>
       <td>{{ f[i].username  }} <b>{{ f[i].sobrename }}</b></td>
       <td>{{ f[i].last_seen }}</td>
    </tr>
{% endfor %}

This way you are limiting correctly and showing the corresponding object at that position i of the list.

  • Thanks worked... You can help me I have a database with several names, I wanted you to show me only the last 5 records so I did {% for i in range(5, 0, -1) %} just so show me the last 5, wanted you to show me the last one you logged into the database

  • Opa @Dalmocabral if it worked can mark the answer as accepted? About this problem, you have to change the query. If your table is indexed, you can sort the elements (ORDER BY) by the decreasing index or if you have any insertion date may be as well. This treatment should be done primarily in the query pq it is very heavy to treat later on the front.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.