Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(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.

like image 648
André Pletschette Avatar asked Oct 16 '22 04:10

André Pletschette


1 Answers

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.

like image 131
Nikolas Charalambidis Avatar answered Oct 27 '22 22:10

Nikolas Charalambidis