Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

python - Using index from iterated list

I'm trying to display values from a different list based on the index that is currently being iterated over on another list but cannot figure out how to access the individual items..

{% for row in myarray.all %}
    <tr>
    <th>{{ my_other_array_where_I_cant_access_elements.forloop.counter }}</th>
    <td>{{ row }}</td>
    </tr>
{% endfor %}

As you can see I have tried to use forloop.counter but this doesn't display anything, it just creates an empty table header element.

My other array is defined within the view as the following, and if I remove the forloop.counter then I am able to see the entire array printed to the table header

 my_other_array_where_I_cant_access_elements = ["X", "Y", "Z", "XX", "YY"]

Please let me know if I've missed any required details.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like you want to iterate over two lists at the same time, in other words zip() lists.

If this is the case, it is better to do this in the view and pass inside the context:

headers = ["X", "Y", "Z", "XX", "YY"]
data = zip(headers, myarray.all())
return render(request, 'template.html', {'data': data})

Then, in the template:

{% for header, row in data %}
    <tr>
        <th>{{ header }}</th>
        <td>{{ row }}</td>
    </tr>
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...