【发布时间】:2022-01-24 22:49:50
【问题描述】:
我想遍历一个项目列表并将它们放在一个表格中,但我希望表格在 x 个项目之后中断。我正在使用 bootstrap5 来格式化我的表格。
我想将以下字典显示为表格:
{'store_6': [ProductData(id=1516004, stat=0), ProductData(id=1516028, stat=2)]}
{'store_3': [ProductData(id=590418, stat=5), ProductData(id=590422, stat=1), ProductData(id=590423, stat=1), ProductData(id=590424, stat=2), ProductData(id=590425, stat=0), ProductData(id=590427, stat=4), ProductData(id=590432, stat=0)), ProductData(id=1590418, stat=0), ProductData(id=1590422, stat=0), ProductData(id=1590423, stat=0), ProductData(id=1590424, stat=0), ProductData(id=1590425, stat=0), ProductData(id=1590427, stat=2), ProductData(id=1590432, stat=0)), ProductData(id=1690418, stat=0), ProductData(id=1690422, stat=0), ProductData(id=1690423, stat=1), ProductData(id=1690424, stat=3), ProductData(id=1560425, stat=0), ProductData(id=1690427, stat=5), ProductData(id=1690432, stat=0))]}
每一行都以商店名称开头,然后为每个产品使用一列。如果商店有超过 10 种产品,则第一列为空白。产品数量不得超过 32 个。
我有一个可行的解决方案,但它看起来......古怪:
{% for store_number, products in all_store_data.items %}
{% for product in products %}
{% if forloop.first %}
<tr>
<td class="col-sm-2">{{ store_number }}</td>
{% endif %}
{% if forloop.counter == 11 or forloop.counter == 21 or forloop.counter == 31 %}
<tr>
<td class="col-sm-2"></td>
{% endif %}
<td class="col-sm-1">
{{ product.id }}
</td>
{% if forloop.last %}
{% for add_row in forloop.counter|fill_until_10 %}
<td class="col-sm-1"></td>
{% endfor %}
{% endif %}
{% if forloop.counter|modulo:10 %}
</tr>
{% endif %}
{% endfor %}
{% endfor %}
带有两个小辅助过滤器:
@register.filter
def modulo(num, val):
return num % val == 0
@register.filter
def fill_until_10(counter):
return range(10 - counter % 10)
我现在的问题是,我真的不认为模板中的代码“易于阅读”——有人对如何处理这个问题有更好的了解吗?
我想避免使用mark_safe 魔法,因此尽量避免使用额外的模板过滤器。
【问题讨论】:
-
您愿意使用桌子以外的东西吗?它似乎不适合您的数据
-
不...我真的很想呆在桌子上,因为它可以帮助我避免很多
<div>魔术:) -
仅供参考,你的
modulo过滤器docs.djangoproject.com/en/4.0/ref/templates/builtins/…已经有一个内置版本了
标签: django django-templates django-template-filters