簡體   English   中英

使用自定義比較器對 Thymeleaf 模板中的列表進行排序

[英]Sorting lists in Thymeleaf template using a custom comparator

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)}

在我的文檔模型中,我有一個帶有鍵值對的映射列表(來自 JBake 靜態頁面生成器的published_content列表)。 在我的模板中,我想通過比較地圖中某個鍵下存儲的值來對這個列表進行排序。

換句話說, list變量的類型為List<Map<String, Object>> ,我想通過比較存儲在鍵"mykey"下的每個映射中的值來對這個列表進行排序。

如何在模板中制定這樣的比較器?

該問題與純 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 對列表進行排序后,您可以使用 Thymeleaf 表達式${#lists.sort(list, comparator)}如文檔中所述。

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

<span th:each="doc : ${#lists.sort(documents, new com.mycompany.myapp.comparator.DocumentNameComparator())}">
    ...
</span>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM