Counters in Loops in Thymeleaf

前端 未结 2 1250
再見小時候
再見小時候 2021-02-12 20:49

Is there a way to do a loop in Thymeleaf without a list?

I\'d like to essentially convert this snippet to Thymeleaf:



        
相关标签:
2条回答
  • 2021-02-12 21:04

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

    0 讨论(0)
  • 2021-02-12 21:16

    You can use the special thymleaf iteration variable inside the each block. This special variable name is the name of your element variable concatenate with the keyword 'Stat' (ex: elt -> eltStat) This variable gives you many information related to the iteration.

    You can also specify this variable name after your element variable. For example:

    <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
        <td th:text="${prod.name}">Onions</td>
        <td th:text="${prod.price}">2.41</td>
        <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>
    

    More information in the official documentation below:
    http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#keeping-iteration-status

    0 讨论(0)
提交回复
热议问题