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

SpringBoot MVC项目中Thymeleaf的each循环放置box类div的问题

Thymeleaf循环渲染box元素解决方案

th:each属性会作用于它所在的标签,被修饰的标签会按遍历集合的元素数重复生成,标签内部所有子元素都可以访问当前遍历到的单个对象。
你当前的写法将th:each放在了外层普通div上,会导致每遍历一篇博客就生成一次「标题+描述+空box」的结构,box没有和对应博客内容绑定,不符合需求。

方案1:标题、描述放入box内(大部分场景的需求)

如果你的需求是每篇博客对应一个完整的box容器,所有博客内容都放在box内部,写法如下:

<div class="box" style="width:100%" th:each="blogPost : ${BlogPosts}">
    <div class="glass"></div>
    <div class="content" style="padding:0; margin:0; align-items: center;">
        <h3 th:text="${blogPost.title}"></h3>
        <p th:text="${blogPost.description}"></p>
    </div>
</div>

方案2:标题、描述放在box外部

如果你的需求是标题、描述在box外,仅box元素随每篇博客重复渲染,写法如下:

<div style="align-items: center" th:each="blogPost : ${BlogPosts}">
    <h3 th:text="${blogPost.title}"></h3>
    <p th:text="${blogPost.description}"></p>
    <div class="box" style="width:100%">
        <div class="glass"></div>
        <div class="content" style="padding:0; margin:0;">
            <!-- 此处可添加需要在box内渲染的博客内容 -->
        </div>
    </div>
</div>

内容的提问来源于stack exchange,提问作者Miko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 13:48:02