Skip to main content
 首页 » 编程设计

python之如何迭代 Django 模板中的列表

2024年08月23日31JeffreyZhao

<分区>

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

View .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 但无济于事。我该如何解决这个问题?