首页 > 解决方案 > How to create table with dynamically rows and columns with number of fields in template Django

问题描述

I want to create dynamically rows and columns table in Django with number. Like the attached picture below

<table border="1">
                    {% for i in row %}
                        <tr>
                            {% for x in columns %}
                                <td>????</td>
                            {% endfor %}
                        </tr>
                    {% endfor %}
                </table>

enter image description here

标签: pythondjango

解决方案


根据您想要 3 列和 n 行的图片,您可以将列表拆分为具有 3 个元素的子列表。

在您的 views.py 中执行此操作:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  
n = 3 #elements per sublist
  
final_list = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] 

确保您将 final_list 传递给您的模板。

在模板中,您可以遍历列表并构建您的表格,如:

<table>
  {% for sublist in final_list %}
    <tr>
      {% for element in sublist %}
        <td>element</td> 
      {% endfor %}
    </tr>
  {% endfor %}
</table> 

推荐阅读