Search code examples
javaspringspring-bootspring-mvcthymeleaf

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


Solution

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