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

如何在Thymeleaf中获取List嵌套Map结构的指定键对应值

Thymeleaf Map取值问题解决方案

问题根因

你的items是List<Map<String, Object>>类型,外层循环拿到的item本身就是Map对象。你第二层的th:each="element : ${item}"遍历的是Map的Entry集合,得到的element是Map.Entry类型,只能通过element.key取键名、element.value取对应值。你要的projectName是外层item Map中的键,所以直接从item对象取值即可。

场景1:遍历Map所有键值对,所有链接href统一用当前行的projectName

如果你需要把Map内所有字段都逐列展示,且每列的链接都指向当前行对应的projectName,直接调整取值逻辑即可:

<tr th:each="item : ${items}">
    <td th:each="element : ${item}">
           <a th:text="${element.value}"
                th:href="${item.projectName}">anchor</a>
    </td>
</tr>

Thymeleaf中Map取值支持三种等价写法,可根据习惯选择:

  • ${item.projectName}(点语法,推荐)
  • ${item['projectName']}
  • ${item.get('projectName')}

场景2:仅单独展示指定字段,不需要全量遍历Map

如果你不需要列出Map所有字段,只需要取projectName、modelName等指定字段,不需要加第二层循环,直接取值即可:

<tr th:each="item : ${items}">
    <!-- 项目名列,点击跳转到对应项目页面示例 -->
    <td>
        <a th:text="${item.projectName?: '无项目名'}" 
           th:href="@{/project/detail(projectId=${item.id})}">项目名称</a>
    </td>
    <!-- 其他指定字段列 -->
    <td th:text="${item.modelName}"></td>
    <td th:text="${item.user_poi_no}"></td>
</tr>

注意事项

  • 涉及路径跳转时推荐用@{}语法包裹,会自动拼接项目上下文路径,避免部署后路径错误
  • 不确定Map是否存在对应键时可以用?:设置默认值,避免空值报错

内容的提问来源于stack exchange,提问作者emarwa.mouma.35t

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:36:03