【问题标题】:create table with dynamic rows and columns with django html template使用 django html 模板创建具有动态行和列的表
【发布时间】:2018-07-22 20:01:03
【问题描述】:

我正在尝试使用 django html 模板根据结果列表创建具有动态行和列的表。记录数和标题编号可能会发生变化。我正在使用两个 for 循环来获取行数和列数。我很难尝试输出表中的实际值。这个想法是从第二个 for 循环“索引”并将其应用于第一个循环的“每个”。我知道语法肯定是错误的,但是 django 可以做到吗?如果没有,我有什么建议可以研究如何实施吗?谢谢!!

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

list_2 = [
  {'header_c': c_foo1, 'header_d': d_foo1}, 
  {'header_c': c_foo2, 'header_d': d_foo2},
]

Sample Table 2
header_c | header_d
c_foo1   | d_foo1
c_foo2   | d_foo2

<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>

【问题讨论】:

  • 该列表是来自模型单个查询集还是由多个查询集组成,因此需要按顺序排列?您可以发表您的观点以便我们提供帮助吗?
  • 这是从单个查询集返回的数据。
  • 好的,但是,列标题如何动态更改?如果模型已经设置,除非您更改模型,否则它应该是相同的字段。
  • 后端正在运行动态 sql 查询。列数可能因给定条件而异。
  • 嗯,好吧,让我检查一下

标签: javascript html django django-templates frontend


【解决方案1】:

好吧,由于您在该架构中有一个字典列表,因此您可以在模板中对其进行迭代:

<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>

假设您在每个字典中都有相同的键(列标题或您命名的字段),您首先只迭代第一个字典以获取其键,然后再次迭代行的值...

虽然不是最有效的解决方案,但如果您可以重写创建该列表的方式,那就太好了。

希望对你有帮助,请确认它是否有效

【讨论】:

    【解决方案2】:

    也许您应该查看django tables?这是使用 django 创建功能强大的表的众所周知的工具。您可以基于模型创建它们,但也可以简单地将数据直接传递给它们。我也曾经用它来创建一个动态表。它从模板中获取所有工作并将其添加到更易于操作的视图中。

    【讨论】:

    • 我曾想过使用 django 表格,但我最终想要构建的表格将由下拉菜单、输入文本框和其他按钮组成。
    • 我明白了。好吧,他们有一个名为 TemplateColumn(django-tables2.readthedocs.io/en/latest/pages/…) 的列类型,您可以在其中将列定义为模板,因此您可以简单地传递下拉模板、输入模板或任何您喜欢的内容。
    猜你喜欢
    • 2011-04-12
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多