Search code examples
javathymeleafnested-loops

How to display a table dynamically in Thymleaf with Java?


How can I display a table in HTML code using Thymleaf and Java?

Backend: (I created a HTML Template with TemplateEngine)

private Map<String, Object> createAdditionalContext() {

  Map<String, Object> additionalContext = new HashMap<>();

  ArrayList<Integer> rows = new ArrayList<>();
  ArrayList<Integer> columns = new ArrayList<>();

  // Number of columns and rows in the table
  int numColumns = 10;
  int numRows = 1;


 for (int i = 0; i <= 0; i++) {
     rows.add(i);

     for (int j = 1; j <= 25; j++) {
         columns.add(j);

         // FIXME
         if (j % 5 == 0) {
             rows.add(i);
             break;
         }
     }
 }

 additionalContext.put("rows", rows);
 additionalContext.put("columns", columns);

 return additionalContext;
}

Frontend:

<table>
   <tbody>
      <tr th:each="row: ${rows}">
         <td th:each="col: ${columns}" th:text="${col}"></td>
      </tr>
   </tbody>
</table>

Output now:

1 2 3 4 5
1 2 3 4 5

Output should be:
1 2 3 4 5 1 2 3 4 5
6 7 8 9 10 6 7 8 9 10
11 12 13 14 15 11 12 13 14 15
16 17 18 19 20 16 17 18 19 20
21 22 23 24 25 21 22 23 24 25

Solution

  • I simplified the 2 blocks to one. After that you just have to copy the line and so you have 2 blocks next to each other.

    Backend:

    private Map<String, Object> createAdditionalContext() {
       Map<String, Object> additionalContext = new HashMap<>();
    
       int[][] array = new int[5][5];
       int number = 1;
    
       for (int i = 0; i < array.length; i++) {
           for (int j = 0; j < array[i].length; j++) {
               array[i][j] = number;
               number++;
           }
       }
    
       additionalContext.put("array", array);
    
       return additionalContext;
    }
    

    Frontend:

    <table>
       <tbody>
          <tr th:each="row : ${array}">
            <td th:each="element : ${row}" th:text="${element}"></td>
            <td th:each="element : ${row}" th:text="${element}"></td>
          </tr>
       </tbody>
    </table>