Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count number of rows in flask templates

i have send a variable from my views to templates which consist of the data from database

this is what i am using in my template

{% for i in data %}             
    <tr>
        <td>{{i.id}}</td>
        <td>{{i.first_name}}</td>
        <td>{{i.last_name}}</td>
        <td>{{i.email}}</td>
    </tr>
{% endfor %}

there are seven entries in this loop , i need to show count lease suggest how can i do this

like image 999
Rohit Goel Avatar asked Jul 19 '13 06:07

Rohit Goel


2 Answers

Inside the loop you can access a special variable called loop and you can see the number of items with {{ loop.length }}

This is all you can do with loop auxiliary variable:

  • loop.index The current iteration of the loop. (1 indexed)

  • loop.index0 The current iteration of the loop. (0 indexed)

  • loop.revindex The number of iterations from the end of the loop (1 indexed)

  • loop.revindex0 The number of iterations from the end of the loop (0 indexed)

  • loop.first True if first iteration.

  • loop.last True if last iteration.

  • loop.length The number of items in the sequence.

  • loop.cycle A helper function to cycle between a list of sequences. See the explanation below.

  • loop.depth Indicates how deep in deep in a recursive loop the rendering currently is. Starts at level 1

  • loop.depth0 Indicates how deep in deep in a recursive loop the rendering currently is. Starts at level 0

EDIT:

To see the count of items outside de for loop you can generate another variable from your view like count_data = len(data) or you can use the length filter:

Data count is {{ data|length }}:
{% for i in data %}
    <tr>
      <td>{{i.id}}</td>
      <td>{{i.first_name}}</td>
      <td>{{i.last_name}}</td>
      <td>{{i.email}}</td>
    </tr>
{% endfor %}
like image 96
Diego Navarro Avatar answered Oct 17 '22 04:10

Diego Navarro


{{ data|length }}

this works perfect we not need to use this in loop just use any where in the template even we dont need to send another variable from views

like image 29
Rohit Goel Avatar answered Oct 17 '22 05:10

Rohit Goel