for loop template

23 views
Skip to first unread message

Luca Bertolotti

unread,
Oct 4, 2019, 10:51:44 AM10/4/19
to Django users
from the view i give to the template the following variables

selezione = Dbasedett.objects.filter(idbase=mod_id, revdbase=rev_test)
lista = ['test', 'test_one']

Than i return render(.........{'selezione':selezione, 'lista':lista}

In the form i need to do this:

<table>
        
        {% for dati in selezione %} 
            <tr class={% cycle 'odd' 'even' %}>
            <td>{{ dati.pos }}</td> <td>{{ dati.matr }}</td> <td>{{ lista.forloop.counter0 }}</td>
            </tr>
        {% endfor %}

But {{ lista.forloop.counter0 }} is empty 

Any help

thanks
       

Jani Tiainen

unread,
Oct 4, 2019, 11:04:21 AM10/4/19
to django...@googlegroups.com
Counter0 only exists for variables declared within template itself for for loops. Lista isn't for loop variable and thus it's always empty.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ebb1381a-02a7-46b9-b9c1-0d064596bed7%40googlegroups.com.

Pradeep Sukhwani

unread,
Oct 7, 2019, 4:16:33 AM10/7/19
to Django users
Hi Luca,

As far as I'm able to understand you need to print the elements in the lista array corresponding to the current forloop.counter0, if this is the case then you can do:

{% load index %}
{{ lista|index:forloop.counter0 }} // this will print the element in the lista array corresponding to the current forloop counter

Note: I have created the custom template filter like:

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
   
return indexable[i]

Docs: Django (For creating the custom template filter)
Example: StackOverflow

--
Thanks
Pradeep Sukhwani
Reply all
Reply to author
Forward
0 new messages