How can I get a specific map value from Thymeleaf?
<tr th:each="item : ${items}">
<td th:each="element : ${item}">
<a th:text="${element['key']}">anchor</a>
</td>
</tr>
In the code above, all keys corresponding to an element are displayed.
But what I want is to get element['projectName']
.
That is, I want it to be something like this:
<tr th:each="item : ${items}">
<td th:each="element : ${item}">
<a th:text="${element['key']}"
th:href="${element.get('projectName')}">anchor</a>
</td>
</tr>
The data type of items is List<Map<String, Object>>
, and the values in items are
assertThat(innerItems.get(0).get("modelName")).isEqualTo("a");
assertThat(innerItems.get(0).get("item")).isEqualTo(1);
assertThat(innerItems.get(0).get("id")).isEqualTo("q");
assertThat(innerItems.get(0).get("projectName")).isEqualTo("DefaultProject");
assertThat(innerItems.get(0).get("user_poi_no")).isEqualTo(1);
is.
CodePudding user response:
Looks like it would be better to loop by key in your inner loop if I get it right.
<tr th:each="item : ${items}">
<td th:each="key: ${item.keySet()}">
<a th:text="${key}" th:href="${item.get(key)}">anchor</a>
</td>
</tr>
CodePudding user response:
When you loop over a map, you get a special java.util.Map.Entry
element with a key
and a value
, not the actual item itself. In the example you gave, using item
instead of element
should work (if that is indeed what you want):
<tr th:each="item : ${items}">
<td th:each="element : ${item}">
<a th:text="${element['key']}" th:href="${item['projectName']}">anchor</a>
</td>
</tr>
If you just wanted the projectName
from each item in your list, you don't even need the inner loop. Like this for example:
<tr th:each="item : ${items}">
<td>
<a th:text="${item['projectName']}">anchor</a>
</td>
</tr>