django - 将列表呈现为 django 模板中的 2 列 html 表

标签 django django-templates

我有一个有序列表,我将它呈现为 Django 模板中的 2 列 html 表。在表中,应输出元素,使前 (n+1)/2 个元素在第一列中,其余元素在第二列中,如下所示:

<table>
  <tr>
     <td>Elem 1</td>
     <td>Elem 4</td>
  </tr>
  <tr>
    <td>Elem 2</td>
    <td>Elem 5</td>
  </tr>
  <tr>
    <td>Elem 3</td>
    <td></td>
  </tr>
</table>

假设我的元素在上下文中为 {{ elems }} ,我怎么能在 Django 模板中合理地完成这个?

最佳答案

查询 this recipe .你可能需要修改它,但你会明白的。

使用它,在您的模板中,您只需执行以下操作:

{% for row in elems|columns:2 %}
 <tr>
    {% for item in row %}
        <td>{{ item }}</td>
    {% endfor %}
 </tr>
{% endfor %}

关于django - 将列表呈现为 django 模板中的 2 列 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11864580/

相关文章:

python - Django 应用程序中的 Azure 云存储配置错误 : Could not load Azure bindings

jquery - twitter bootstrap 下拉列表在 django 模板中不起作用

django - 如何在 div 的 html 背景 url 中使用产品图片? Django

django - 尝试使用Django中的套接字创建聊天应用程序

html - Django 表单与传统表单

python - Django 迭代 ClearableFileInput 小部件字段

python - 如何使用 Tox 和 Poetry 在 CircleCI 中设置多个解释器?

python - UWSGI 堆栈转储

Django:如何显示我自己的动态创建的字段

python - 如何修复-没有这样的表 : main. auth_user__old