André Pletschette
André Pletschette

Reputation: 302

(Spring) th:with based on a condition

I want to assign a variable in thymeleaf based on a condtion:

<span th:with="valueID=${${myField != null} ? {myField.value.getId()}}">

This does not work, and gives me an exception:

"Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: `"${myField == null} ? {myField.value.getId()}"`"

What am I doing wrong?

In fact I want to set valueID to {myField.value.getId()} when myField is not null.

Upvotes: 5

Views: 753

Answers (1)

Nikolas
Nikolas

Reputation: 44476

Using ? operator should be enough:

<span th:with="valueID=${myField?.value.getId()}">

The getter method can be omitted to:

<span th:with="valueID=${myField?.value.id}">

However, the code is still not null-safe since value can be null as well.

Upvotes: 3

Related Questions