I’m trying to iterate an string in Thymeleaf, letter by letter:
<div th:each="i: ${#numbers.sequence(0, #strings.length(name))}">
<p th:text="${name.charAt(i)}"></p>
</div>
This is giving me an error:
Caused by: org.attoparser.ParseException: Exception evaluating
SpringEL expression: "name.charAt(i)" (template: "name-list" – line 8,
col 16) at
org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393) at
org.attoparser.MarkupParser.parse(MarkupParser.java:257) at
org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
… 48 more
If I do
<div th:each="i: ${#numbers.sequence(0, #strings.length(name))}">
<p th:text="${name.charAt(2)}"></p>
</div>
Thymeleaf does not complain and gives me what I want. Thank you.
>Solution :
Your index is going out of bounds. Subtract one from the length of the string for the endpoint of the sequence (which is inclusive).
<div th:each="i: ${#numbers.sequence(0, #strings.length(name) - 1)}">
You can directly use [i] to access the character by index rather than charAt also.
<p th:text="${name[i]}"/>
To avoid working with indexes, you can loop over the characters of the string (obtainable by calling toCharArray()).
<div th:each="c: ${name.toCharArray()}">
<p th:text="${c}"/>
</div>