Home > Software design >  Django access array with forloop.counter in template
Django access array with forloop.counter in template

Time:07-31

I have an array ['one', 'two', 'three']

In my django template i want to access to elements of the array like that:

{% for a in array %} 
  {{ array.loop.counter}}    
{% endif %}

But array.loop.counter return nothing. There is a way to access the element of the array based on the loop counter of my for ?

CodePudding user response:

Why not just do this?:

{% for a in array %} 
  {{ a }}    
{% endif %}

CodePudding user response:

Ok I find a way to do it.

create a template tag into templatetags repository.

Use this custom filter:

from django import template

register = template.Library()

@register.filter(name='index')
def index(sequence, position):
    return sequence[position]

Then into the template :

{{ array|index:forloop.counter }}
  • Related