You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

1. Fixing the Dynamic Value Expression in Thymeleaf

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.

2. The More Direct Way: Pass the Entire Map to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 16:40:49