Velocity模板中第二个foreach循环生成重复值,求解决建议
解决Velocity模板中foreach循环生成重复值的问题
看起来你遇到的核心问题是内部的foreach($rs in $risks)循环会遍历所有风险记录,导致每个工作项(workitem)行里重复输出所有风险的P/A/C/E评级单元格,不仅生成重复值,还会破坏表格的列结构(原本表格只有14列,现在每多一条风险就会多4列)。下面给你几个针对性的解决思路:
1. 关联工作项与对应风险(最推荐)
如果每个工作项应该对应专属的风险记录,那你需要确保$workitem对象本身带有关联的风险集合(比如$workitem.relatedRisks),然后只遍历当前工作项的风险,而不是全局的$risks集合。修改后的代码如下:
#foreach($workitem in $workitems) #set($wiType = $workitem.fields().type().optionId()) <tr> <td> $projectId</td> <td></td> <td>$workitem.fields.docNumber.render </td> #if($wiType.equals("document")) <td>$workitem.fields().description.render()</td> #else <td></td> #end <td></td> <td></td> <td></td> #if($wiType.equals("requirement")) <td>$workitem.fields().description.render()</td> #else <td></td> #end <td>$workitem.fields().type().render()</td> <td>$workitem.fields.discipline.render</td> <!-- 只遍历当前工作项关联的风险 --> #foreach($rs in $workitem.relatedRisks) <td>$rs.fields.P.render</td> <td>$rs.fields.A.render</td> <td>$rs.fields.C.render</td> <td>$rs.fields.E.render</td> #end </tr> #end
这样每个工作项只会输出自己对应的风险数据,不会重复渲染全局的所有风险。
2. 用循环索引匹配一一对应的工作项与风险
如果$workitems和$risks是按顺序一一对应的(比如第1个workitem对应第1个风险,第2个对应第2个),那可以直接用循环索引来获取对应风险,完全去掉内部的foreach循环:
#foreach($workitem in $workitems) #set($wiType = $workitem.fields().type().optionId()) #set($riskIndex = $foreach.index) <!-- 获取当前工作项的循环索引 --> #set($currentRisk = $risks.get($riskIndex)) <!-- 匹配对应索引的风险 --> <tr> <td> $projectId</td> <td></td> <td>$workitem.fields.docNumber.render </td> #if($wiType.equals("document")) <td>$workitem.fields().description.render()</td> #else <td></td> #end <td></td> <td></td> <td></td> #if($wiType.equals("requirement")) <td>$workitem.fields().description.render()</td> #else <td></td> #end <td>$workitem.fields().type().render()</td> <td>$workitem.fields.discipline.render</td> <!-- 直接输出对应风险的评级,无需循环 --> <td>$currentRisk.fields.P.render</td> <td>$currentRisk.fields.A.render</td> <td>$currentRisk.fields.C.render</td> <td>$currentRisk.fields.E.render</td> </tr> #end
这种方式适合两个集合长度完全一致、顺序严格对应的场景,能彻底避免重复值问题。
3. 确保风险是单个对象而非集合
如果每个工作项只对应一条风险记录,那$risks应该是单个对象(而不是集合),这时候直接输出风险属性即可,不需要foreach循环:
#foreach($workitem in $workitems) #set($wiType = $workitem.fields().type().optionId()) <tr> <td> $projectId</td> <td></td> <td>$workitem.fields.docNumber.render </td> #if($wiType.equals("document")) <td>$workitem.fields().description.render()</td> #else <td></td> #end <td></td> <td></td> <td></td> #if($wiType.equals("requirement")) <td>$workitem.fields().description.render()</td> #else <td></td> #end <td>$workitem.fields().type().render()</td> <td>$workitem.fields.discipline.render</td> <!-- 直接输出单个风险的评级 --> <td>$risks.fields.P.render</td> <td>$risks.fields.A.render</td> <td>$risks.fields.C.render</td> <td>$risks.fields.E.render</td> </tr> #end
这种情况适合全局只有一条风险,或者每个工作项的风险是单独传入模板的场景。
内容的提问来源于stack exchange,提问作者user13500535
相关产品推荐
相关产品推荐

