相关疑难解决方法(0)

迭代Django模板中的两个列表

我想在django模板中进行以下列表迭代:

foo = ['foo', 'bar'];
moo = ['moo', 'loo'];

for (a, b) in zip(foo, moo):
    print a, b
Run Code Online (Sandbox Code Playgroud)

django代码:

{%for a, b in zip(foo, moo)%}
  {{a}}
  {{b}}
{%endfor%}
Run Code Online (Sandbox Code Playgroud)

我尝试这个时收到以下错误:

File "/base/python_lib/versions/third_party/django-0.96/django/template/defaulttags.py", line 538, in do_for
    raise TemplateSyntaxError, "'for' statements should have either four or five words: %s" % token.contents
Run Code Online (Sandbox Code Playgroud)

我该如何做到这一点?

python django django-templates

33
推荐指数
4
解决办法
4万
查看次数

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

我将 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 …
Run Code Online (Sandbox Code Playgroud)

python django django-templates

6
推荐指数
1
解决办法
7877
查看次数

标签 统计

django ×2

django-templates ×2

python ×2