首页 > 解决方案 > 执行 <#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

解决方案


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>

请注意,groupNamegroupItemsin<@listGroups ...>只是您指定的任意循环变量名称,它们不需要与#macro定义中使用的变量名称匹配。


推荐阅读