freemarker - 执行 <#list> 时如何正确分组记录
问题描述
新人来了 我一直在 NetSuite 中构建一个高级表单(使用 Freemarker)来显示发票数据。一切看起来和工作都很好,但是,我想按位置对发票行项目进行分组。我正在使用一个简单的 <#list> 循环来提取行项目记录。我目前在每个订单项上显示位置。
代码(为简单起见删除了格式/样式):
<table>
<#list record.item as item>
<tr>
<td> ${item.location} </td>
<td> ${item.description} </td>
<td> ${item.quantity} </td>
<td> ${item.rate} </td>
<td> ${item.amount} </td>
</tr>
</#list>
</table>
电流输出示例:
Location A Des 1 1 $100 $100
Location B Des 1 1 $100 $100
Location C Des 1 1 $100 $100
Location A Des 2 1 $100 $100
Location B Des 2 1 $100 $100
Location C Des 2 1 $100 $100
Location A Des 3 1 $100 $100
Location C Des 3 1 $100 $100
所需的输出示例:
Location A
Des 1 1 $100 $100
Des 2 1 $100 $100
Des 3 1 $100 $100
Location B
Des 1 1 $100 $100
Des 2 1 $100 $100
Location C
Des 1 1 $100 $100
Des 2 1 $100 $100
Des 3 1 $100 $100
我试图嵌套第二个 <#list> 但它不能正常工作。任何建议或指示都会有助于将我推向正确的方向。
谢谢!
解决方案
FreeMarker 期望这样的分组由任何设置变量来完成,在本例中是 NetSuite。(但是,我认为这可能被视为纯粹的演示问题,因此也许 FreeMarker 应该在将来处理这个问题。)如果 NetSuite 确实不会为您分组数据,那么您必须在 FreeMarker 中进行,这将有点尴尬,因为它不是真正的编程语言......但它就是这样。
像这样定义一个宏:
<#macro listGroups items groupField>
<#if items?size == 0><#return></#if>
<#local sortedItems = items?sort_by(groupField)>
<#local groupStart = 0>
<#list sortedItems as item>
<#if !item?is_first && item[groupField] != lastItem[groupField]>
<#local groupEnd = item?index>
<#nested lastItem[groupField], sortedItems[groupStart ..< groupEnd]>
<#local groupStart = groupEnd>
</#if>
<#local lastItem = item>
</#list>
<#local groupEnd = sortedItems?size>
<#nested lastItem[groupField], sortedItems[groupStart ..< groupEnd]>
</#macro>
您可以稍后像这样使用此宏:
<@listGroups record.item "location"; groupName, groupItems>
<p>${groupName}</p>
<table>
<#list groupItems as groupItem>
<tr>
<td>${groupItem.location}</td>
<td>${groupItem.description}</td>
<td>${groupItem.quantity}</td>
<td>${groupItem.rate}</td>
<td>${groupItem.amount}</td>
</tr>
</#list>
</table>
</@listGroups>
请注意,groupName
和groupItems
in<@listGroups ...>
只是您指定的任意循环变量名称,它们不需要与#macro
定义中使用的变量名称匹配。
推荐阅读
- r - 从矩阵和栅格计算 wasserstein 度量
- android - 无法在华为设备上为 H264 编码视频设置远程 SDP 报价
- mysql - 使用 Laravel Eloquent 模型查询多个表关系
- python - 如果 sql 有日期条件,pyodbc 结果返回空
- javascript - 触发缓存以确保数据正确问题 - swr 挂钩 - next.js(使用打字稿)
- webix - 带有水平滚动条的树表
- java - 如果连接丢失,我想显示以前的数据而不是空列表
- docker - docker run --entrypoint "python /path/to/file.py" 导致“没有这样的文件或目录:未知。” 错误
- python - 如何在我的 Django+drf-yasg 项目中使用 editor.swagger.io 中的 swagger.json?
- ubuntu - 在 ubuntu linux 中以 root 权限运行 VS Code 不再起作用