Thymeleaf中如何通过变量选择另一个变量?Map传入Model问题
Hey there! I see you've run into two related issues: getting dynamic values from your split Model attributes in Thymeleaf, and not realizing you can pass the entire Map directly to the Model. Let's break this down clearly.
Your ${${k}} syntax doesn't work because Thymeleaf doesn't support nested expression evaluation like that. If you've already added the keys list and individual value lists to the Model (using each key as the attribute name for its corresponding list), you need to use Thymeleaf's built-in #vars object to dynamically fetch the attribute by name.
Here's the corrected code:
<!-- Iterate over your keys list --> <ul th:each="k : ${keys}"> <li th:text="${k}">Key Name</li> <!-- Use #vars.get(k) to dynamically get the list for this key --> <ul th:each="item : ${#vars.get(k)}"> <li th:text="${item}">List Item</li> </ul> </ul>
The #vars object represents the current context's variable collection (your Model attributes). Calling #vars.get(k) takes the value of k (e.g., "fruit" or "vegetables") and pulls the corresponding list from the Model.
You don't need to split your Map<String, List<String>> into separate keys and lists at all! Spring's Model fully supports complex collection types like this. This approach is cleaner and avoids the dynamic attribute lookup hassle.
Step 1: Add the Map to Model in your Controller
// Assume your Map is named myStringListMap model.addAttribute("myStringListMap", myStringListMap);
Step 2: Use the Map directly in Thymeleaf
You have two easy options here:
Option 1: Iterate over the Map's key-value pairs
This is great if you want to process every entry in the Map:
<div th:each="entry : ${myStringListMap}"> <h4 th:text="${entry.key}">Key</h4> <ul> <li th:each="item : ${entry.value}" th:text="${item}">List Item</li> </ul> </div>
Option 2: Iterate over keys and fetch values manually
If you need to control the order of keys (e.g., using a sorted keys list), you can still do this with the full Map:
<!-- You can get the keys directly from the Map, or pass a sorted list if needed --> <ul th:each="k : ${myStringListMap.keySet()}"> <li th:text="${k}">Key</li> <!-- Use either map.get(k) or map[k] syntax to fetch the list --> <ul th:each="item : ${myStringListMap.get(k)}"> <li th:text="${item}">List Item</li> </ul> </ul>
内容的提问来源于stack exchange,提问作者chris01

