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

如何使用Thymeleaf将动态图片集展示为3×3矩阵(支持扩展)

用Thymeleaf实现动态3×3图片矩阵展示

要实现图片按3×3矩阵批量展示、超出自动新增矩阵的需求,可以通过Thymeleaf的集合处理和循环结合数学计算来完成,以下是具体实现方案:

核心思路

  1. 将图片集合按每9个元素划分为一个子集合,对应一个完整的3×3矩阵;
  2. 每个矩阵内部按3行3列的网格结构渲染;
  3. 针对每个网格位置,计算其对应的全局图片索引,存在图片则渲染,不存在则显示空位。

实现代码

HTML(Thymeleaf模板)

假设后端传递的图片集合为List<Image> images,每个Image对象包含图片URL属性url:

<!-- 矩阵容器,多个矩阵可并排展示 -->
<div class="matrix-container" th:each="matrixIdx : ${#numbers.sequence(0, ( #lists.size(images) + 8 ) / 9 - 1)}">
  <!-- 单个3×3矩阵 -->
  <div class="grid-3x3">
    <!-- 循环渲染3行 -->
    <div class="grid-row" th:each="rowIdx : ${#numbers.sequence(0, 2)}">
      <!-- 循环渲染3列 -->
      <div class="grid-item" th:each="colIdx : ${#numbers.sequence(0, 2)}">
        <!-- 计算当前网格对应的全局图片索引 -->
        <th:block th:with="imgIndex=${matrixIdx * 9 + rowIdx * 3 + colIdx}">
          <!-- 存在图片则渲染 -->
          <img th:if="${imgIndex < #lists.size(images)}" 
               th:src="${images[imgIndex].url}" 
               alt="展示图片" 
               class="grid-img"/>
          <!-- 无图片则显示空位 -->
          <div th:unless="${imgIndex < #lists.size(images)}" class="empty-item"></div>
        </th:block>
      </div>
    </div>
  </div>
</div>

CSS样式(实现网格布局)

/* 矩阵容器,支持多个矩阵横向排列 */
.matrix-container {
  display: inline-block;
  margin: 10px;
}

/* 3×3网格布局 */
.grid-3x3 {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 6px;
}

/* 网格项基础样式 */
.grid-item {
  width: 120px;
  height: 120px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

/* 图片自适应填充 */
.grid-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

/* 空位样式 */
.empty-item {
  background-color: #f5f5f5;
  border-radius: 4px;
}

关键细节说明

  • ( #lists.size(images) + 8 ) / 9:计算需要生成的总矩阵数,通过向上取整的方式确保所有图片都能被覆盖;
  • matrixIdx * 9 + rowIdx * 3 + colIdx:通过矩阵索引、行索引、列索引计算当前网格对应的全局图片位置;
  • th:if/th:unless:判断当前位置是否有图片,实现图片与空位的动态切换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:30:24