Javascript 使用django html模板创建具有动态行和列的表
我正在尝试使用django html模板基于结果列表创建一个包含动态行和列的表。记录数和标题号可能会更改。我使用两个for循环来获得行数和列数。我很难在表中输出实际值。其想法是从第二个for循环中“索引”,并将其应用于第一个循环的“每个”。我知道语法肯定是错误的,但django能做些什么吗?如果没有,我有什么建议可以研究如何实现这一点?谢谢Javascript 使用django html模板创建具有动态行和列的表,javascript,html,django,django-templates,frontend,Javascript,Html,Django,Django Templates,Frontend,我正在尝试使用django html模板基于结果列表创建一个包含动态行和列的表。记录数和标题号可能会更改。我使用两个for循环来获得行数和列数。我很难在表中输出实际值。其想法是从第二个for循环中“索引”,并将其应用于第一个循环的“每个”。我知道语法肯定是错误的,但django能做些什么吗?如果没有,我有什么建议可以研究如何实现这一点?谢谢 list = [ {'header_a': foo1, 'header_b': foo2, 'header_c': foo3}, {'header_
list = [
{'header_a': foo1, 'header_b': foo2, 'header_c': foo3},
{'header_a': foo1, 'header_b': foo2, 'header_c': foo3},
{'header_a': foo3, 'header_b': foo3, 'header_c': foo3},
{'header_a': foo4, 'header_b': foo4, 'header_c': foo4},
]
Sample Table
header_a | header_b | header_c
foo1 | foo1 | foo1
foo2 | foo2 | foo2
foo3 | foo3 | foo3
foo4 | foo4 | foo4
或
{列表中索引的%0%}
{{index}}
{%endfor%}
{列表%中的每一个都为%1}
{%用于%中的索引}
{{each.{index}}}
{%endfor%}
{%endfor%}
也许你应该退房?使用django创建功能强大的表是一个非常有名的工具。您可以基于模型创建它们,但也可以直接将数据传递给它们。我还曾经用它来创建一个动态表。它从模板中获取所有作业,并将其添加到更易于操作的视图中。好吧,由于该模式中有一个字典列表,因此您可以在模板中迭代它:
<table>
<thead>
<tr>
{% for item in list %}
{% if forloop.first %}
{% for h in item %}
<th>{{ h }}</th>
{% endfor %}
{% endif%}
{% endfor %}
</tr>
</thead>
<tbody>
{% for item in list %}
<tr>
{% for key,value in item.items %}
<td>{{ value}}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{列表%中的项目的%s}
{%if-forloop.first%}
{项目%中h的%s}
{{h}
{%endfor%}
{%endif%}
{%endfor%}
{列表%中的项目的%s}
{%为键,值在item.items%}
{{value}}
{%endfor%}
{%endfor%}
假设每个字典中都有相同的键(列标题或字段,如您命名的),首先只迭代第一个字典以获取其键,然后再次迭代行的值
这不是最有效的解决方案,如果你能重写你创建列表的方式,那就太好了
希望有帮助,请确认它是否有效该列表是来自一个模型的单个查询集还是由多个查询集组成的,所以它需要这样的顺序?您能发布您的视图以便我们提供帮助吗?它是从单个查询集返回的数据。好的,但是,列标题如何可以动态更改?,如果已设置模型,则除非更改模型,否则该模型应为相同的字段。后端正在运行动态sql查询。根据给定的条件,列的数量可能会有所不同。嗯,好吧,让我检查一下。我曾想过使用django表,但我最终想要构建的表将由下拉列表、输入文本框和其他按钮组成。我明白了。它们有一个名为TemplateColumn()的列类型,您可以将该列定义为模板,因此只需传递下拉模板、输入模板或任何您喜欢的内容。
<table>
<thead>
<tr>
{% for index in list.0 %}
<th>{{ index }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for each in list %}
<tr>
{% for index in a %}
<td>{{ each.{{index}} }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<table>
<thead>
<tr>
{% for item in list %}
{% if forloop.first %}
{% for h in item %}
<th>{{ h }}</th>
{% endfor %}
{% endif%}
{% endfor %}
</tr>
</thead>
<tbody>
{% for item in list %}
<tr>
{% for key,value in item.items %}
<td>{{ value}}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>