簡體   English   中英

Thymeleaf:如何處理復雜的地圖鍵

[英]Thymeleaf: How to deal with complex map keys

我得到了Map<Bean,List<AnotherBean>>形式的Map<Bean,List<AnotherBean>> ,我需要訪問 Thymeleaf 上的鍵值字段,有沒有辦法做到這一點? 還是我注定要尋找另一種方法來做到這一點? 到目前為止我嘗試過的:

<div th:each="entry: ${map.keySet()}">  
     <span  th:text="${entry.field}"></span>

和 :

<div th:each="entry: ${map}">   
     <span  th:text="${entry.key.field}"></span>

兩次我都遇到了同樣的錯誤:

org.springframework.expression.spel.SpelEvaluationException:EL1008E:在“java.lang.String”類型的對象上找不到屬性或字段“field”——可能不是公共的或無效的?

有人可以幫忙嗎?

在我看來, ${map.keySet()}正在返回一個列表......不知道這是百里香葉問題,還是存在於您的數據結構中,但我建議嘗試類似的方法

List<String> headers = new ArrayList<>();
map.forEach((key, value) -> {
    headers.add(key.getFIeld());
};
context.setVariable("tableHeaders", headers );

對模板中的 map.values() 也使用類似的方法,現在您可以直接對 tableHeaders 和值進行迭代。

 <div class = "container">
     <h2 th:text="${title}"></h2>
     <table id="myTable" class = "table">
         <tr>
             <th th:each = "header : ${tableHeaders}" th:text="${header}"></th>
         </tr>
          <tr th:each = "record : ${records}">
              <td th:each="element : ${record}" th:text="${element}"></td>
          </tr>
       </table>
   </div>

我知道這更像是一種解決方法,但是如果它沒有選擇這件事中的字段,您可以放心,問題出在構成您映射的關鍵參數的 Bean 中

暫無
暫無

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

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