【问题标题】:How to iterate over a list in django templates? [duplicate]如何遍历 django 模板中的列表? [复制]
【发布时间】:2015-12-26 21:35:20
【问题描述】:

我将 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 %}

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

【问题讨论】:

  • 基本上,你不能,但你真的应该考虑拥有一个实际的模型

标签: python django django-templates


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-05-15
    • 1970-01-01
    • 2010-10-21
    • 2018-02-24
    • 2023-03-06
    • 1970-01-01
    • 2020-04-04
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多