如何迭代django模板中的列表?

时间:2015-12-26 21:35:20

标签: python django django-templates

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

views.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))})

allbooks.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 %}

我尝试用{%forloop.counter0%}替换变量x,但无济于事。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

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

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

在模板中循环覆盖它:

             {% for book in books %}
            <tr>
                <td>{{ book.0 }}</td>
                <td>{{ book.1 }}</td>
                <td>{{ book.2 }} </td>
                <td>{{ book.3 }}</td>
            </tr>
        {% endfor %}

我建议为您的图书信息提供更好的结构:

books = [

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

]

比迭代它:

       {% for book in books %}
            <tr>
                <td>{{ book.id }}</td>
                <td>{{ book.name }}</td>
                <td>{{ book.author }} </td>
                <td>{{ book.copies }}</td>
            </tr>
        {% endfor %}