Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Thymeleaf loop error when using its index

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading