Django counter in loop to index list

前端 未结 5 435
鱼传尺愫
鱼传尺愫 2020-12-29 12:33

I\'m passing two lists to a template. Normally if I was iterating over a list I would do something like this

{% for i in list %}

but I hav

5条回答
  •  长情又很酷
    2020-12-29 13:28

    To access an iterable using a forloop counter I've coded the following very simple filter:

    from django import template
    
    register = template.Library()
    
    @register.filter
    def index(sequence, position):
        return sequence[position]
    

    And then I can use it at my templates as (don't forget to load it):

    {% for item in iterable1 %}
      {{ iterable2|index:forloop.counter0 }}
    {% endfor %}
    

    Hope this helps someone else!

提交回复
热议问题