25

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?

Lucky
  • 16,787
  • 19
  • 117
  • 151
rwinner
  • 348
  • 3
  • 6
  • 15
  • 1
    ${#numbers.sequence( 1, 81/20)} -> What is this. Does this internally tells that it is to be run over this range OR is it something we are explicitly mentioning somewhere – Dhiraj Gandhi Nov 29 '17 at 15:22

4 Answers4

16

Add step to your code is quite easy.

#{numbers.sequence(0, 81, 20)}
windX
  • 174
  • 1
  • 5
12

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> 
sitakant
  • 1,766
  • 2
  • 18
  • 38
7

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.

JaanRaadik
  • 571
  • 3
  • 11
  • I knew that, this was just an attempt, I want the thymeleaf to do the same as the Java code. – rwinner Dec 17 '13 at 14:07
  • then you could change the thymeleaf code to 'numbers.sequence( 0, 4)' – JaanRaadik Dec 17 '13 at 14:11
  • the number 81 is out of 100, this number is actually some number from the model, i just typed it in hardcoded for readability – rwinner Dec 17 '13 at 14:21
  • Well then keep the sequence from 0,81/20, i will give the same result. I cannot help you further than suggesting the correct starting number, starting from 0 will give you the results you need. The only reason it is giving incorrect number of loops is you are starting from a different number in each piece of code. – JaanRaadik Dec 18 '13 at 00:01
6

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)}
user2274218
  • 61
  • 1
  • 2