使用Python Jinja生成HTML报告表格时块级tr布局错位如何解决
问题原因
表格错位的核心原因是同一Step ID下的多个子步骤单元格被错误放在了同一个<tr>行标签内:你设置了rowspan让Step ID跨N行,但没有对应生成N个独立的<tr>,导致单行列数超出表格定义的11列,触发错位。
修正后的Jinja代码
<body> <div id="testName"> {{ ca['name'] }} </div> <br> <div id="testDates"> Start test Date: <span>{{ ca['start_ca'] | time_str }}</span> <br> End test Date: <span>{{ ca['end_ca'] | time_str }}</span> </div> {% for stage in ca['stages'] %} <table class="blueTable"> <tbody style="page-break-inside: auto;" > <tr id="rowOne"> <th style="font-weight:bolder;">Stage</th> <th colspan="5">Start Date</th> <th colspan="5">End Date</th> </tr> <tr id="rowTwo"> <td >{{ stage.name }}</td> <td colspan="5">{{stage.start | time_str}}</td> <td colspan="5">{{stage.end | time_str}}</td> </tr> <tr style="background-color: #1C6EA4; color: white;"> <th>Step ID</th> <th>Step</th> <th>Start Date</th> <th>End Date</th> <th>Expected</th> <th>Found</th> <th>Not Found</th> <th>Expected Ok</th> <th>Ok</th> <th>Fails</th> <th>Overall</th> </tr> {%for step in stage.steps%} {% set step_child_count = step[1] | size %} {% for s in step[1] %} <!-- 每个子步骤单独生成一行 --> <tr class="filaBucle"> <!-- 只有第一个子步骤输出带rowspan的Step ID列 --> {% if loop.first %} <th rowspan='{{ step_child_count }}'> {{step[0]}} </th> {% endif %} <th >{{s.name}}</th> <td>{{s.start | time_str}}</td> <td>{{s.end | time_str}}</td> <td style="color:darkblue;">{{s.expected}}</td> <td style="color:green;">{{s.found}}</td> <td style="color:red;">{{s.not_found}}</td> <td style="color:darkblue;">{{s.expected_ok}}</td> <td style="color:green;">{{s.ok}}</td> <td style="color:red;">{{s.fails}}</td> {% if s.overall < 50 %} <td style="color: red;">{{s.overall}}%</td> {% elif 50 <= s.overall < 100 %} <td style="color: brown;">{{s.overall}}%</td> {% else %} <td style="color: green;">{{s.overall}}%<br></td> {% endif %} </tr> {% endfor %} {% if step[1] | has_errors %} <tr style="color: #F3E9EB;background-color: #8E8585; border-style: hidden;"> <th colspan="11"> Errors Details</th> </tr> {%for s in step[1]%} {% if s.error_detail %} <tr style="color: #D22020; background-color: #D3C9C9;"> <th colspan="2">Step ID: {{s._id}}</th> <th colspan="9"> {{s.name}}</th> </tr> {% for detail in s.error_detail %} <tr style="color: #D22020; background-color: #D3C9C9;"> <td colspan="11"> {{detail | replace("\n", "<br>")}}</td> </tr> {% endfor %} {% endif %} {% endfor %} {% endif %} {% endfor %} </tbody> </table> {% endfor %}
额外优化说明
- 原代码中循环生成的
id="filaBucle"会导致HTML id重复,改为class="filaBucle"符合规范 - 不需要额外调整CSS,修正DOM结构后表格会自动按行列规则正常渲染
内容的提问来源于stack exchange,提问作者LuisferHacking
相关产品推荐
相关产品推荐

