【问题标题】:Loop list of list item dynamically in Django templates在 Django 模板中动态循环列表项的列表
【发布时间】:2021-10-18 03:45:56
【问题描述】:

我的列表中的列表如下所示:

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}} 方法循环它,因为列表会根据选择的客户端数量而变化。所以我需要动态循环它。

我尝试使用方法in this link,但没有成功,因为我不断收到错误list indices must be integers or slices, not str

有什么办法可以做到吗?

【问题讨论】:

  • 您的预期输出是什么?另外为什么不能使用{{ c.0 }} 语法?它与客户数量无关。
  • @Selcuk 他不能使用{{ c.0 }},因为他不知道c 有多少元素。有些可能有 3 个,有些可能有 4 个,等等。
  • @JohnGordon 好吧,您可能是对的,但这不是我最初阅读问题的方式:“列表将根据选择的客户数量而变化”

标签: python django


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-02-15
    • 2015-11-05
    • 2019-05-06
    • 1970-01-01
    • 2015-11-23
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多