【问题标题】:How to iterate over a list value of a dictionary in django template如何在 django 模板中迭代字典的列表值
【发布时间】:2018-07-31 16:55:57
【问题描述】:

我有一本字典,其中值在列表中

{
    'Fees': ['88000', '88000'],
    'ROll Number': ['I0', 'I1'],
    'Mark': [10, 10]
}

所以我试图在表中插入这些数据,所以我的 Django 模板是

  <table>
      <thead>
        <tr>
        {% for k, v in loan_bank_info.items %}
            <th>{{ k }}</th>
        {% endfor %}
        </tr>
      </thead>
      <tbody>
      <tr>
      {% for k, value in loan_bank_info.items %}
        {% for v in value %}  
          <td>{{ v }}</td>
          {% endfor %}
      {% endfor %}
      </tr>
    </tbody>
  </table>

但表中的值打印如下,

  Fees          ROll Number     Mark
  88000 88000    I0 I1           10 10

但我想要的是-

Fees            ROll Number     Mark
  88000          I0             10 
  88000          I1             10

如何在 Django 模板中迭代列表值

【问题讨论】:

  • 我认为您需要将&lt;tr&gt;&lt;/tr&gt; 标签放在外部for 循环内

标签: python django dictionary django-templates


【解决方案1】:

您可以遍历列表。如下所示

<tr>
      {% for k, value in loan_bank_info.items %}
        {% for v in value %}
            {% for i in v %} 
              <td>{{ i }}</td>
            {% endfor %}
          {% endfor %}
      {% endfor %}
      </tr>

【讨论】:

  • TypeError: 'int' 对象不可迭代
  • 这就是他们已经在做的事情。添加另一个级别的迭代现在将尝试迭代整数值本身。我无法测试,但我认为问题至少部分是由于&lt;tr&gt; 在最外层循环之外,但是没有理由从 OP 已经拥有的另一个内部循环中获得
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2019-02-05
  • 2014-01-13
  • 1970-01-01
  • 2021-01-16
相关资源
最近更新 更多