本文介绍了Thymeleaf 循环中的计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在没有列表的情况下在 Thymeleaf 中进行循环?
我想基本上将此代码段转换为 Thymeleaf:
<fmt:formatDate var="year" value="${now}" pattern="yyyy"/><c:forEach var="i" begin="0" end="99"><form:option value="${year-i}"/></c:forEach></form:select>
-- 更新--
我已经决定这符合我想要的方式,但我不确定 springEL 语法:
<option th:each="i : ${#numbers.sequence( 1, 100)}" th:value="#{ T(java.util.Date).getYear() - $i }">1</option>
解决方案
如果您仍在寻找正确的 SpEL 语法,这对我有用:
1</option>
注意:
- 添加了
th:text
以设置选项文本. - 改用 Joda-Time 因为
java.util.Date
不会给我想要的结果
阅读关于 java.util.Date 和 getYear() 的讨论>
Is there a way to do a loop in Thymeleaf without a list?
I'd like to essentially convert this snippet to Thymeleaf:
<jsp:useBean id="now" class="java.util.Date" />
<fmt:formatDate var="year" value="${now}" pattern="yyyy" />
<c:forEach var="i" begin="0" end="99">
<form:option value="${year-i}" />
</c:forEach>
</form:select>
-- Update --
I've decided this is along the lines of how I want to do it, but I'm not sure about the springEL syntax:
<option th:each="i : ${#numbers.sequence( 1, 100)}" th:value="#{ T(java.util.Date).getYear() - $i }">1</option>
解决方案
In case you are still looking for the correct SpEL syntax,here's what worked for me:
<option th:each="i : ${#numbers.sequence( 1, 100)}"
th:value="${ (new org.joda.time.DateTime()).getYear() - i }"
th:text="${ (new org.joda.time.DateTime()).getYear() - i }">1</option>
Notice:
- added
th:text
to set the option text. - used Joda-Time instead as
java.util.Date
wouldn't give me the desired outcome
Read this discussion on java.util.Date and getYear()
这篇关于Thymeleaf 循环中的计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!