Laika_Boss
Laika_Boss

Reputation: 75

Thymeleaf results in error when using variable inside an expression

For the provided string in my model, I want to print a "growing" list of substrings. For example, if the given string is Wine, the result should be:

W
Wi
Win
Wine

I've come up with the following construct:

<h1 th:with="len=${#strings.length(name)}" th:each="i : ${#numbers.sequence(1, ${len})}" th:text="${#strings.substring(name, 0, i)}"></h1>

but it doesn't work.

If I change ${#numbers.sequence(1, ${len})} to ${#numbers.sequence(1, 4)} it works. However, this way I'd need to manually change the code whenever my initial string's length changes.

I've tried with messages.msg() alternative, but no luck either.

Error:


An error happened during template parsing (template: "class path resource [templates/name-list.html]")
Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "#numbers.sequence(1, ${len})" (template: "name-list" - line 7, col 53)

What am I doing wrong?

Upvotes: 0

Views: 191

Answers (1)

Metroids
Metroids

Reputation: 20477

  1. th:each has a higher attribute precedence than th:with. Since th:each is evaluated first, the len variable is not available here.

  2. In most cases, you should not/cannot nest ${...} expressions. If the len variable was available here, you should have used len instead of ${len}.

.

<h1
  th:each="i : ${#numbers.sequence(1, #strings.length(name))}"
  th:text="${#strings.substring(name, 0, i)}" />

Upvotes: 1

Related Questions