print key/value in thymeleaf from hashmap/arraylist

蓝咒 提交于 2019-12-11 08:11:18

问题


The code in java/springboot:

@RequestMapping(value = "results")
public String results(
        Model model, 
        @RequestParam String searchType,
        @RequestParam String searchTerm) {

    model.addAttribute("columns", ListController.columnChoices);
    ArrayList<HashMap<String, String>> jobsbyval = JobData
            .findforValue(searchTerm);
    model.addAttribute("items", jobsbyval);
    return "search";
}

The code in html/thymeleaf:

<div>
  <table>
    <tbody>
      <tr th:each="item : ${items}">
        <!--each loop begins -->
        <td th:text="${item}"></td> //item.value or item.key dont work!!

      </tr>
      <!--loop ends -->
    </tbody>
  </table>
</div>

Here is the html ouput.

{header 1=something, header 2=Analyst, category 3=somename, location=somewhere, skill=Stats}

The desired HTML output(key/value) in table format would be:

header 1  something  
header 2  Analyst 
category  somename 
location  somewhere 
skill Stats

回答1:


Yes, it does not work because items (or jobsbyval) is not a map but it is a list of maps, namely: ArrayList<HashMap<String, String>> jobsbyval.

Your thymeleaf snippet just prints the string representation of the first and only map within the list. If you need to iterate all maps within the list you need a nested loop, for example:

Model:

    List<Map<String, String>> mapsList = new ArrayList<Map<String, String>>();

    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("keyinmap1", "valueinmap1");
    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("keyinmap2", "valueinmap2");

    mapsList.add(map1);
    mapsList.add(map2);

    modelMap.put("mapsList", mapsList);

View:

<div th:each="map : ${mapsList}">
     <div th:each="mapEntry : ${map}">
         <span th:text="${mapEntry.key}"></span> = 
         <span th:text="${mapEntry.value}"></span> 
     </div>
</div>

Output:

keyinmap1 = valueinmap1
keyinmap2 = valueinmap2

th:each accept maps, in this case:

When iterating maps, iter variables will be of class java.util.Map.Entry

For details - see here.



来源:https://stackoverflow.com/questions/42966653/print-key-value-in-thymeleaf-from-hashmap-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!