问题
How can I do the following (java):
for(int i = 0; i < 81 ; i+=20){
//Should loop through 5 times!
}
in Thymeleaf?
I've tried this:
<option th:each="i : ${#numbers.sequence( 1, 81/20)}">
<p th:text="${ i }"></p> <!-- THIS loops 4 times, instead of 5 -->
</option>
The problem is that it is not as accurate as the java piece of code. How to do this?
回答1:
I am assuming this is due to the numbers you are using. For your java code, int i = 0; i < 81 ; i+=20 will return i=0, i=20, i=40, i=60 and i=80
however your following code numbers.sequence( 1, 81/20)} should returns the integers from 1 to 4.05, being 1, 2, 3, and 4.
The first loop returns 5 results for i, therefore runs 5 times. the second returns only 4 results, so runs 4 times. I would suggest running your sequence starting at 0 to return 5 results as desired.
If you wanted your java code to mirror the second code, you should change it to: int i = 1; i < 4.05 ; i+=1
To put it simply, you are running through a loop with different numbers, I suggest changing the second statement to start from 0.
回答2:
use iterStat key word to iterate. Example If you have an Array of String and you are iterating the same using thymeleaf.
<div th:each="str,iterStat : strings">
<span th:text="${str}"/><!--This will print the index value-->
<span th:text="${iterStat.index}"/><!--This will print the Index-->
</div>
回答3:
Add step to your code is quite easy.
#{numbers.sequence(0, 81, 20)}
回答4:
The 1st value is the beginning of count, the 2nd is the maximum value and the 3rd is the incremental value
${#numbers.sequence( 1, 4, 1)}
来源:https://stackoverflow.com/questions/20633118/for-loop-in-thymeleaf