首页 > 解决方案 > 在 HTML 表格中显示上下文变量

问题描述

我想要做的是用与我的字典中的条目相同的行数填充一个 html 表。我将我的字典项作为上下文变量传递给 html。我可以按如下方式显示我的字典项目:

{% for key,value in top_items.items %}
<ul>{{ key }}</ul>
{% endfor %}

但是当我尝试将其粘贴到表格中以创建表格行时,如下所示,它不起作用。似乎将它们全部排成一排。而不是为每个项目创建一个新行。

    <table class="u-half-width">
  <thead>
    <tr>
      <th>Column</th>
        <th>Details</th>
    </tr>
  </thead>
  <tbody>
    <tr>
        {% for key,value in top_items.items %}
        <tr>{{ key }}</tr>
        {% endfor %}
    </tr>
  </tbody>
</table>

标签: htmlhtml-table

解决方案


您的 HTML 无效;您不能将 a 嵌套<tr>在 another<tr>中,并且您没有任何<td>/<th>元素。

尝试:

<tbody>
    {% for key,value in top_items.items %}
    <tr>
        <th scope="row">{{ key }}</th>
        <td>{{ value }}</td>
    </tr>
    {% endfor %}
</tbody>

推荐阅读