Alan Tingey Alan Tingey -4 years ago 244
Python Question

Counter within django loop

I have the following django / html code:

{% for x in fixtures %}

<div id="match1" style="display:block">{{x.home_team.teamname}}</div>

{% endfor %}

The above simply displays all teams from a set of fixtures. It works perfectly as it stands. However, I would like the div id to go up 1 each time it runs through the loop. I.e "match1" then "match2" then "match3" etc.

I am assuming javascript is my friend here? but some direction would be appreciated.

Many thanks in advance for any assistance :)

Answer Source

There's no need for javascript. You can use the forloop.counter variable:

{% for x in fixtures %}

    <div id="match{{ forloop.counter }}" style="display:block">{{x.home_team.teamname}}</div>

{% endfor %}

The various variables available in a for loop are described in the docs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download