Search code examples
javahtmlspring-mvcdictionarythymeleaf

What is the EL syntax to render a map into a table in Thymeleaf?


I have a map that I would like to render into a table in Thymeleaf. Each key is a document title and each value is an integer displaying the number of times a keyword appears in that document.

HTML:

<table class="table table-striped table-bordered table-hover">
   <tr>
      <td>Document Title</td>
      <td>Keyword Count</td>
   </tr>
   <tr th:each="m : ${map}">
      <td th:text="${m} + '(' + ${map.get(key)} + ') '"></td>
      <td th:text="${m} + '(' + ${map.get(value)} + ') '"></td>
   </tr>
</table>

Map:

   Map<String, Integer> map = combineListsIntoOrderedMap(formattedLinks, countList);

   private static Map<String, Integer> combineListsIntoOrderedMap(List<String> keys, List<Integer> values) {
        if (keys.size() != values.size())
            throw new IllegalArgumentException("Cannot combine lists with dissimilar sizes.");
        Map<String, Integer> map = new LinkedHashMap<>();
        for (int i = 0; i < keys.size(); i++) {
            map.put(keys.get(i), values.get(i));
        }
        return map;
    }

My output is a table that looks like this:

Document Title  | Keyword Count
http://www.example.com/doc.doc=1(null) | http://www.example.com/doc.doc=1(null)

It should look like:

Document Title  | Keyword Count
http://www.example.com/doc.doc | 1

Solution

  • You can use key and value like this:

    <tr th:each="m : ${map}">
        <td th:text="${m.key}">key</td>
        <td th:text="${m.value}">value</td>
    </tr>