如何遍历 django 模板中的列表?

Ava*_*is 6 python django django-templates

我将 4 个相同长度的列表和列表的长度传递给我的模板。如何遍历列表?

视图.py

def allbooks(request):
    ID = [1,2]
    bookName = ["Python", "Java"]
    author = ["idk", "who"]
    copies = [3,7]
    return render(request, 'allbooks.html',{'ID':ID,'bookName':bookName, 'author':author, 'copies':copies,'range':range(len(ID))})
Run Code Online (Sandbox Code Playgroud)

全书.html

{% extends 'base.html' %}

{% block content %}
{% if user.is_authenticated %}
<div>
    <h3>
        List of books:
    </h3>
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Book Name</th>
                <th>Author</th>
                <th>Number of copies</th>
            </tr>
        </thead>
        <tbody>
            {% for x in range %}
                <tr>
                    <td>{{id[x]}}</td>
                    <td>{{bookName[x]}}</td>
                    <td>{{author[x]}}</td>
                    <td>{{copies[x]}}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</div>    
{% else %}
    <h3>You must login to continue.</h3>    
{% endif %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

我试过用 {% forloop.counter0 %} 替换变量 x 但无济于事。我怎样才能解决这个问题?

Big*_*her 12

将所有列表压缩到一个元组列表中:

 books= zip(ID, bookName, author, copies)
 return render(request, 'allbooks.html',{ "books": books} )
Run Code Online (Sandbox Code Playgroud)

比在模板中循环它,如:

             {% for book in books %}
            <tr>
                <td>{{ book.0 }}</td>
                <td>{{ book.1 }}</td>
                <td>{{ book.2 }} </td>
                <td>{{ book.3 }}</td>
            </tr>
        {% endfor %}
Run Code Online (Sandbox Code Playgroud)

我为您的图书信息建议了一个更好的结构:

books = [

{ "id":1, "name": "Python", "author":"idk", "copies": 1},
{ "id":2, "name": "Java", "author":"idk2", "copies": 3}

]
Run Code Online (Sandbox Code Playgroud)

而不是遍历它:

       {% for book in books %}
            <tr>
                <td>{{ book.id }}</td>
                <td>{{ book.name }}</td>
                <td>{{ book.author }} </td>
                <td>{{ book.copies }}</td>
            </tr>
        {% endfor %}
Run Code Online (Sandbox Code Playgroud)