我需要对记录列表进行排序并将它们呈现在表中,但它们必须按“起始日期”列排序,然后在第二级按“截止日期”排序。我检查了 文档中的 ?sort_by 但它没有提到任何对双重排序的支持。
以为这些会起作用,但它正在做不同的事情。
<#list invoices?sort_by(['from_date', 'to_date']) as inv>
<#list invoices?sort_by("from_date")?sort_by("to_date") as inv>
此外,某些记录的“起始日期”或“截止日期”值为空。
我最终做了类似于这个问题的事情,但必须添加一些解析并在表格底部呈现带有空日期的记录。
我的 Freemarker 代码的改编:
<table>
<tr>
<th>name</th>
<th>quantity</th>
<th>dateFrom</th>
<th>dateTo</th>
</tr>
<#assign fromDates = "" />
<!-- Sort records by from_date, then to_date -->
<#list records?filter(x -> x.custcol_from_date?has_content && x.custcol_to_date?has_content)?sort_by("custcol_from_date") as record>
<#assign currentFrom = record.custcol_from_date />
<#if !(fromDates?has_content)>
<#assign prevFrom = currentFrom />
<#assign fromDates = currentFrom + "---" />
</#if>
<#if prevFrom != currentFrom>
<#assign fromDates = fromDates + currentFrom + "---" />
</#if>
<#assign prevFrom = currentFrom />
</#list>
<#list fromDates?split("---") as fromDate>
<#if fromDate?has_content>
<#assign parsedDate = fromDate?date />
<#list records?filter(x -> x.custcol_from_date?has_content && x.custcol_to_date?has_content && x.custcol_from_date = parsedDate)?sort_by("custcol_to_date") as record>
<tr>
<td>${record.name}</td>
<td>${record.quantity}</td>
<td>${record.custcol_from_date}</td>
<td>${record.custcol_to_date}</td>
</tr>
</#list>
</#if>
</#list>
<!-- Print entries without from/to date at the end of table -->
<#list records?filter(x -> !x.custcol_from_date?has_content || !x.custcol_to_date?has_content) as record>
<tr>
<td>${record.name}</td>
<td>${record.quantity}</td>
<td>${record.custcol_from_date}</td>
<td>${record.custcol_to_date}</td>
</tr>
</#list>
</table>
可以在 https://try.freemarker.apache.org/ 更改此行进行测试:
<#assign parsedDate = fromDate?date />
到
<#assign parsedDate = fromDate />
数据模型:
records=[ { "name": "One", "quantity": "10", "custcol_from_date": "2024-05-31", "custcol_to_date": "2024-06-01" }, { "name": "Two", "quantity": "20", "custcol_from_date": "2024-05-31", "custcol_to_date": "2024-06-15" }, { "name": "Three", "quantity": "30", "custcol_from_date": "2024-05-31", "custcol_to_date": "2024-06-01" }, { "name": "Four", "quantity": "40", "custcol_from_date": "2024-05-31", "custcol_to_date": "2024-07-02" }, { "name": "Five", "quantity": "50", "custcol_from_date": "2024-04-01", "custcol_to_date": "2024-06-01" }, { "name": "Six", "quantity": "60", "custcol_from_date": "2024-04-02", "custcol_to_date": "2024-05-10" }, { "name": "Seven", "quantity": "70", "custcol_from_date": "2024-05-01", "custcol_to_date": "" }, { "name": "Eight", "quantity": "80", "custcol_from_date": "2024-04-01", "custcol_to_date": "2024-05-13" }, { "name": "Nine", "quantity": "90", "custcol_from_date": "", "custcol_to_date": "2024-06-01" }, { "name": "Ten", "quantity": "100", "custcol_from_date": "", "custcol_to_date": "" } ]
结果: