如何使用Thymeleaf的th:*标签实现JSTL的<c:forEach begin="1" end="12" var="item"/>功能
Hey,刚好做过类似的需求!要替代JSTL里那种指定起始、结束值的<c:forEach>循环,Thymeleaf用内置的工具类就能轻松实现,不用麻烦后端额外传集合。
基础实现(完全对应你的JSTL代码)
核心是用Thymeleaf的#numbers.sequence()方法生成从1到12的整数序列,再配合th:each标签遍历,完美匹配JSTL的功能:
<!-- 等价于<c:forEach begin="1" end="12" var="item"> --> <div th:each="item : ${#numbers.sequence(1, 12)}"> <!-- 循环体内直接用${item}调用当前循环变量,和JSTL用法一致 --> 当前循环项: <span th:text="${item}"></span> </div>
扩展:设置循环步长(对应JSTL的step属性)
如果需要像JSTL那样指定步长,sequence()方法支持第三个参数,比如每次循环递增2:
<!-- 等价于<c:forEach begin="1" end="12" var="item" step="2"> --> <div th:each="item : ${#numbers.sequence(1, 12, 2)}"> 步长为2的循环项: <span th:text="${item}"></span> </div>
实际场景示例:生成月份选择器
这是这类循环最常用的场景之一,快速生成1-12月的下拉选项:
<select name="month"> <option th:each="month : ${#numbers.sequence(1, 12)}" th:value="${month}" th:text="${month}月"> <!-- 静态内容作为无Thymeleaf时的降级显示 --> 1月 </option> </select>
内容的提问来源于stack exchange,提问作者lingkdong
相关产品推荐
相关产品推荐

