Django - 从 views.py 打印多个传递的列表

我有 4 个长度相同的列表,并希望将它们全部传递到 html 页面。

视图.py

return render(request, 'result.html', {'listA':listA, 'listB':listB,  'listC':listC, 'listD':listD})

这是我尝试使用 Flask 时的代码。

应用程序

return render_template('result.html', listA = listA, listB = listB, listC = listC, listD = listD)

下面是模板文件中的代码;使用 Flask,它可以毫无问题地打印出表格,但它似乎不适用于 Django。我应该如何修复我的代码?

结果.html

{% for i in listA %}
<tr>
<th> {{ listA[loop.index] }} </th>
<td> {{ listB[loop.index] }} </td>
<td> {{ listC[loop.index] }} </td>
<td> {{ listD[loop.index] }} </td>
</tr>
{% endfor %}
恶魔

您应该使用自定义模板标签来实现查找,因为 django 没有为您提供。然后使用 django 模板引擎for 循环获取forloop.counter0

首先在您的应用程序文件夹中创建templatetags目录__init__.py让我们假设您的应用程序被称为polls文件夹结构将如下所示:

polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        lookup.py
    views.py

在写进去的查找代码之后lookup.py

from django import template

register = template.Library()

@register.filter
def lookup(d, key):
    return d[key]

最后在模板文件中使用它:

{% load lookup %}
...
{% for i in listA %}
    <tr>
        <th> {{ listA|lookup:forloop.counter0 }} </th>
        <td> {{ listB|lookup:forloop.counter0 }}</td>
        <td> {{ listC|lookup:forloop.counter0 }}</td>
        <td> {{ listD|lookup:forloop.counter0 }}</td>
    </tr>
{%  endfor %}
...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章