【问题标题】:Iterate Multiple Nested Lists in Flask Template using For loop使用 For 循环在 Flask 模板中迭代多个嵌套列表
【发布时间】:2020-03-02 02:42:50
【问题描述】:

我有如下 Python 列表

[[1, 'sarmad ali', 10], [2, 'nabeel', 200], [3, 'tayyab', 40202]]

我想在模板(html页面)中以表格/二维样式显示它们

1 萨马德阿里 10

2 纳比尔 200

3 泰亚布 40202

我可以得到以下内容

1 sarmad ali 10 2 nabeel 200 3 tayyab 40202

在我的python文件中,我有Dataframe形式的数据,并转换为list

{% for col in data_list%}
    
    {% for row in col%}
        
        <td>{{row}}</td>
    
    {% endfor %}
    
    <br>

{% endfor %}

上面的嵌套循环以单行而不是表格格式生成输出。 我发现第二个循环是在单行中迭代所有列表,而不是一次迭代单个列表

如有任何问题,请随时提出更多说明。

【问题讨论】:

    标签: python templates flask jinja2 nested-loops


    【解决方案1】:
    <table>
    {% for sno, name, rank in data_list%}
       <tr>
         <td>{{sno}}</td>
         <td>{{name}}</td>
         <td>{{rank}}</td>
      </tr>
    {% endfor %}
    </table>
    

    编辑: 假设如果您不知道列表中的项目数,

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

    【讨论】:

    • 循环属性未知,它们可以超过三个(sno、名称、等级等)。
    • 你可以再运行一个循环。
    【解决方案2】:

    这是我在模板文件中用来显示列表的内容。

    <div class="content-section">
        <legend class="mb-4"> Table </legend>
    <table class="table" >
    <thead>
        <tr>
          <th scope="col">#</th>
          {%for i in columns%}
          <th scope="col">{{i[0]}}</th>
          {%endfor%}
        </tr>
      </thead>
      <tbody>
    
        {%for i in result%}
    
        <tr>
              <th scope="row">{{loop.index}}</th>
              {%for k in i%}
              <td>{{k}}</td>
              {%endfor%}
          </tr>
    
        {%endfor%}
        </tbody>
    </table>
    
    </div>
    

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多