【问题标题】:Html table renderinghtml表格渲染
【发布时间】:2018-05-31 17:46:19
【问题描述】:

我的 Django 视图正在返回一个字典列表。这通过模板渲染进入 html 表。下面是我的模板代码,

我的字典列表如下所示,

结果:

[{ 'name':'x','age': 20}, {'name': 'y','age': 25 }]

<table class="table table-striped" border="1" class="dataframe"> 
    <thead>
     <tr style="text-align: center;">
     {% for k, v in results.0.items %} 
      <th>{{ k }}</th> 
     {% endfor %}
     </tr> 
    </thead> 
    <tbody> 
       {% for x in results %} 
         <tr style="text-align: center;">
         {% for y in x %}
          <td> {{ x.y }} </td> 
         {% endfor %} 
         </tr> 
       {% endfor %} 
    </tbody> 
</table>

预期输出:

name     age
x        20
y        25

但是输出是空白的。

如果我的 HTML 表格模板有任何问题,请告诉我。

【问题讨论】:

    标签: django templates tagging


    【解决方案1】:

    您可以像外循环一样在内循环中正确使用items

    <div>
        <table class="table table-striped" border="1" class="dataframe">
            <thead>
            <tr style="text-align: center;">
                {% for k, v in results.0.items %}
                <th>{{ k }}</th>
                {% endfor %}
            </tr>
            </thead>
            <tbody>
            {% for x in results %}
    
            <tr style="text-align: center;">
                {% for i,j in x.items %}
                <td> {{ j }} </td>
                {% endfor %}
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 2021-09-23
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多