首页 > 解决方案 > 在 Django 模板中动态循环列表项的列表

问题描述

我在一个看起来像这样的列表中有一个列表:

clientList = [['Client 1', 'Yes', 'No', 'Yes', 'Yes'], ['Client 2', 'No', 'No', 'Yes', 'Yes'], ['Client 3', 'Yes', 'Yes', 'Yes', 'Yes']]

我需要动态调用模板中的列表,如下所示

<table>
  <tr>
    {% for c in clientList %}
    <td>{{c}}</td>
    {% endfor %}
  <tr>
<table>

但它不起作用,因为它看起来像这样:

输出图像

而且我也不能使用该方法循环它,{{c.0}}, {{c.1}}, {{c.3}}, {{c.4}}因为列表会根据选择的客户端数量而变化。所以我需要动态循环它。

我尝试使用此链接中的方法,但它不起作用,因为我一直收到错误list indices must be integers or slices, not str

有什么办法可以做到这一点?

标签: pythondjango

解决方案


请尝试以下。正如你所说,列表中有一个列表。您确实遍历了第一个列表,但忘记了第二个。

    <table>
     <tr>
       {% for c in clientList %}
       {% for a in c %}
       <td>{{a}}</td>
       {% endfor %}
       {% endfor %}
     <tr>
    <table>

推荐阅读