Twig动态表格开发:数组键缺失时如何补全空白单元格
问题根因
列错位的核心原因是渲染表格行的费用列时,仅遍历当前行数组的自有字段,当部分行缺少对应费用字段时,会少渲染对应单元格,导致后续总金额列位置前移。
解决方案
提前统一提取全量表头的所有费用字段,每行渲染时按统一的字段列表遍历,字段不存在时输出空单元格即可保证列数一致。
修改后代码
<table class="table border-top-0 border-bottom small"> {# 提前提取统一的列配置 #} {% set all_columns = ripartoPreventivo|first|keys|slice(1) %} {% set fixed_column_count = 3 %} {# 前3列为固定字段:immobile、interno、condomino #} {% set fee_columns = all_columns|slice(fixed_column_count) %} <thead> <tr class="border-left-0"> {% for titolo in all_columns %} <th class="font-weight-bold text-uppercase text-14">{{titolo}} </th> {% endfor %} <th class="font-weight-bold text-uppercase text-14"> Totale</th> </tr> </thead> <tbody> {% for sub_array in ripartoPreventivo %} <tr> {# 渲染前3个固定字段 #} {% for value in sub_array|slice(1, fixed_column_count) %} <td class="font-weight-bold small">{{ value|raw }}</td> {% endfor %} {# 按统一的费用字段列表渲染,不存在则输出空单元格 #} {% for fee_col in fee_columns %} {% if sub_array[fee_col] is defined %} <td class="font-weight-bold small">€ -{{ sub_array[fee_col].spesa|raw }} <span class="small text-muted"><strong>(mill. {{ sub_array[fee_col].millesimi|raw }})</strong></span></td> {% else %} <td></td> {% endif %} {% endfor %} {# 计算总金额 #} {% set sum = 0 %} {% for fee_col in fee_columns %} {% if sub_array[fee_col] is defined %} {% set sum = sum + sub_array[fee_col].spesa %} {% endif %} {% endfor %} <td class="font-weight-bold small"> € -{{ sum|number_format(2, '.', ',') }}</td> </tr> {% endfor %} </tbody> </table>
内容的提问来源于stack exchange,提问作者pippo
相关产品推荐
相关产品推荐

