Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 273
Sumit Rathore Avatar asked Aug 31 '25 15:08

Sumit Rathore


2 Answers

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>
like image 68
Matt Coubrough Avatar answered Sep 12 '25 18:09

Matt Coubrough


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

like image 21
Prabhat Avatar answered Sep 12 '25 17:09

Prabhat