0

Using Thymeleaf, I am unable to iterate over List<List<String>>

 <tr th:each="row : ${rows}">
      <td th:text="${row[0]}"></td>
      <td th:text="${row[1]}"></td>
 </tr>

Each row has more than 1 value.

When rendering, I am getting the following exception

2016-11-02 20:40:21.033 ERROR 44829 --- [nio-5252-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-5252-exec-1] Exception processing template "completed": Exception evaluating SpringEL expression: "row[1]" (completed:217)
2016-11-02 20:40:21.034 ERROR 44829 --- [nio-5252-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/test-dashboard] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "row[1]" (completed:217)] with root cause

org.springframework.expression.spel.SpelEvaluationException: EL1025E:(pos 3): The collection has '1' elements, index '1' is invalid

Thanks in advance.

Sarath
  • 1,438
  • 4
  • 24
  • 40
  • I'm no thymeleaf expert but I think you cannot access a list element with `row[index]`, maybe `row.get(0)` –  Nov 02 '16 at 15:17
  • @RC Tried that too. Did not help. Throws java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 – Sarath Nov 02 '16 at 15:18
  • 1
    actually, that exception is saying that your row DOESN'T have more than one value: The syntax `row[0]` is working fine, `row[1]` then blows up because there's only 1 value in that sub-list. So that might be your real problem? – David Lavender Nov 02 '16 at 15:34

2 Answers2

2

How about a double loop?

(note that i am not sure about the validity of this XHTML, you might have to use a different HTML element than a SPAN under a TR)

<tr th:each="row : ${rows}">
      <span th:each="s : ${row}">
         <td th:text="${s}"></td>             
      </span>
 </tr>
Mechkov
  • 4,294
  • 1
  • 17
  • 25
  • Awesome! Glad to help! – Mechkov Nov 02 '16 at 16:00
  • Actually, intention was to use the value from the row to be passed to a javascript method. Any suggestion, as in, how can I use it without iterating? So, basically i want to use the 1st three row values to be passed to the javascript method. – Sarath Nov 02 '16 at 16:03
  • Look into the answer to this question: http://stackoverflow.com/questions/25687816/setting-up-a-javascript-variable-from-spring-model-by-using-thymeleaf – Mechkov Nov 02 '16 at 16:05
1

If you just want to generate a TD for each of them, add another for-each, on a TD:

<tr th:each="row : ${rows}">
     <td th:each="rowValue : ${row}" th:text="${rowValue}"></td>
</tr>
David Lavender
  • 8,021
  • 3
  • 35
  • 55