Django counter in loop to index list

前端 未结 5 405
鱼传尺愫
鱼传尺愫 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:06

    You can't. The simple way is to preprocess you data in a zipped list, like this

    In your view

    x = [1, 2, 3]
    y = [4, 5, 6]
    zipped = zip(x, y)
    

    Then in you template :

    {% for x, y in zipped %}
        {{ x }} - {{ y }}
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-29 13:10

    Sounds like you're looking for my django-multiforloop. From the README:

    Rendering this template

    {% load multifor %}
    {% for x in x_list; y in y_list %}
      {{ x }}:{{ y }}
    {% endfor %}
    

    with this context

    context = {
        "x_list": ('one', 1, 'carrot'),
        "y_list": ('two', 2, 'orange')
    }
    

    will output

    one:two
    1:2
    carrot:orange
    
    0 讨论(0)
  • 2020-12-29 13:10

    don't think you'll be able to do it like that. You'll need either a template tag, or much better, to align the lists in your view logic, before passing an aligned data structure to you template.

    0 讨论(0)
  • 2020-12-29 13:16

    I ended up having to do this:

    {% for x in x_list %}
      {% for y in y_list %}
        {% if forloop.counter == forloop.parentloop.counter %}
           Do Something
        {% endif %}
      {% endfor %}
    {% endfor %}
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题