How to use "map.get(key)" in Thymeleaf - Broadleaf Ecom
Asked Answered
C

8

35

I have a Hashmap (String, List<Offers>), passed to a Thymeleaf page. I am getting this map on the page and I can access it.

How can I do map.get(key) with Thymeleaf? I just need to fetch the values based on a certain key and then parse and print that value, which I know and have the logic for.

I am running a Broadleaf application and Thymeleaf is the UI engine for it.

Clementeclementi answered 20/2, 2015 at 3:45 Comment(0)
I
37

Using ${map.get(key)} (where key is a variable) works for me.

${map['key']} only seems to work for String literal keys -- if the key you're looking up is a variable then ${map[key]} doesn't seem to work.

Accessing Map entries given a list of keys

Here's a full example, looking up items in a HashMap map given listOfKeys an ordered List of the keys of elements I want to get from the map. Using a separate listOfKeys like this lets me control the order of iteration, and optionally return only a subset of elements from the map:

<ul>
    <li th:each="key: ${listOfKeys}"">
        <span th:text="${key}"></span> = <span th:text="${map.get(key)}"></span>
    </li>
</ul>

Looping through every entry in a Map

If you do not have an ordered list of keys, but just want to loop through every item in the Map, then you can loop directly through the map's keySet() (But you will have no control of the ordering of keys returned if your map is a HashMap):

<ul>
    <li th:each="key: ${map.keySet()}">
        <span th:text="${key}"></span> = <span th:text="${map.get(key)}"></span>
    </li>
</ul>

This usage can be expressed even more concisely by simply iterating through the entrySet of the map, and accessing each returned entry's key and value members:

<ul>
    <li th:each="entry: ${map}">
        <span th:text="${entry.key}"></span> = <span th:text="${entry.value}"></span>
    </li>
</ul>
Indign answered 31/8, 2017 at 4:46 Comment(1)
I also observe that map['key'] always returns a String. Additionally it seems that map.get('key') also always returns a String. If my map contains an object, how can I return that type in thymeleaf? (Outside of Java, map.get('key').getClass() returns the correct object type).Freak
C
25

You can simply use ${map.get('key')}

Crozier answered 20/2, 2015 at 13:52 Comment(3)
It works with static string, but can you tell me how to do that with a variable?Bowlin
I think instead of static key you can pass variable too... <tr th:each="key : ${list_of_keys}"> <span>${map.get(key)}</span>Crozier
You can pass variable instead of 'key'. If you need to get key per key-value pair, use ${hashMapVariable.getKey()Wesle
P
9

The way to access the value:

${map[__${key}__]}

You have to put the key between doubled underscores to make a pre-processing for the key variable.

Pliocene answered 4/5, 2016 at 14:4 Comment(1)
I observe that map.get('key') and map['key'] work the same way, at least for String type key values.Freak
E
8

I am using with drop down box the following for example to loop keys on maps

<select id="testId">
        <option th:each="item: ${itemsMap}" 
                th:value="${item['key']}"
                th:text="${item['value']}" />
</select>

in case of getting a specific value, I'm using

${itemsMap.get('key')}
Elainaelaine answered 13/9, 2017 at 13:36 Comment(2)
This works but it seems to only ever return a String object, regardless of the object stored in the map. Is this expected?Freak
The key must be an object not primitive type, so it accepts String, Integer, Double. I use it like that in my project, but don't use the quota in those cases.Elainaelaine
U
5

In my situation, where I had a HashMap<String, String>, I had to do the lookup like this

<strong th:text="${map['__${entry.key}__']}"></strong>
Unbent answered 12/9, 2016 at 12:54 Comment(0)
D
3

The way to access the map value for a certain key keyaccess, assuming you have the map mymap in your model:

${mymap['keyaccess']}

That would give you the list associated to your entry, now you could iterate it.

In case you need, you could iterate a map in the same way you could iterate any other supported iterable objects, from the documentation:

Not only java.util.List objects can be used for iteration in Thymeleaf. In fact, there is a quite complete set of objects that are considered iterable by a th:each attribute:

  • Any object implementing java.util.Iterable
  • Any object implementing java.util.Map. When iterating maps, iter variables will be of class java.util.Map.Entry.
  • Any array
  • Any other object will be treated as if it were a single-valued list containing the object itself.
Delorenzo answered 20/2, 2015 at 13:53 Comment(2)
It works with static string, but can you tell me how to do that with a variable?Bowlin
@GregoriusEdwadr ${map[__${key}__]}Brandnew
L
1

remarksMap is TreeMap and "id" is Long type value

<div th:if="${#maps.containsKey(remarksMap, id)}">
   <textarea th:text="${remarksMap.get(id)}" rows="2" cols="30" maxlength="250" 
       autocomplete="off"></textarea>                               
</div>
Levulose answered 17/11, 2018 at 5:16 Comment(0)
L
0

All of the answers lead me in the right direction. The following code from (a table column detail) works:

<td>[[${statusesMap.get('__${employee.status}__')}]]</td>

statusesMap is a Map<String, String> Employee is an employee class with a field called 'status'.

Note the single quotes. It did not work without them.

Leathers answered 11/3, 2022 at 1:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.