如何在 freemarker 模板中排序前更新值

How to update value before sorting in freemarker template

我有以下 html 模板

[#list PRODUCTS?sort_by("Price_origin_type") as product]
[/#list] 

我遇到了以下异常

Exception while merging FreeMarker template with values - ?sort_by(...) failed at sequence index 2 (0-based): All key values in the sequence must be numbers, because the first key value was that. However, the key value of the current item isn't a number.

有没有办法为空值设置 0?

这不会用零替换空值,但应该将它们从列表中排除:

[#list PRODUCTS?filter(p -> p != "")?sort_by("Price_origin_type") as product]
[/#list] 
  1. 在 Java 代码中对 collection 进行排序。
    或者
  2. 在您的 Java dto class.
  3. 中创建一个专用的排序字段
class ProductDto {
  private Integer priceOriginType;
  // other fields

  public int getPriceSortingIndex() {
    return Optional.ofNullable(priceOriginType).orElse(0);
  }
}

并在模板中使用 products?sort_by("priceSortingIndex")