3

Thymeleaf 文档说明了排序列表:

/*
 * Sort a copy of the given list. The members of the list must implement
 * comparable or you must define a comparator.
 */
${#lists.sort(list)}
${#lists.sort(list, comparator)}

在我的文档模型中,我有一个带有键值对的映射published_content列表(来自 JBake 静态页面生成器的列表)。在我的模板中,我想通过比较存储在地图中某个键下的值来对该列表进行排序。

换句话说,list变量具有类型List<Map<String, Object>>,我想通过比较存储在 key 下的每个映射中的值来对该列表进行排序"mykey"

如何在模板中制定这样的比较器?

4

2 回答 2

3

这个问题与纯 Java 排序问题更相关,因为您需要一种对地图列表进行排序的方法,这已经在这里得到了回答。

相关代码:

public Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() {
    public int compare(Map<String, String> m1, Map<String, String> m2) {
        return m1.get("name").compareTo(m2.get("name"));
    }
}

Collections.sort(list, mapComparator);

使用 mapComparator 对列表进行排序后,您可以${#lists.sort(list, comparator)}按照文档中的说明使用 Thymeleaf 表达式。

于 2015-07-13T18:06:54.177 回答
1

在 Thymeleaf 中,您需要使用完整的类名(包括包)。就像是:

<span th:each="doc : ${#lists.sort(documents, new com.mycompany.myapp.comparator.DocumentNameComparator())}">
    ...
</span>
于 2020-05-06T07:58:09.367 回答