Counters in Loops in Thymeleaf

Mouscellaneous picture Mouscellaneous · Apr 9, 2013 · Viewed 32.7k times · Source

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>

Answer

cognant picture cognant · May 19, 2013

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()