0
votes

Conditional Expression (docs):

<tr th:class="${row.even}? 'even' : 'odd'"> 

I want to use conditional expression within a th:field. But every time I try it I get the following error:

*only variable expressions ${...} or selection expressions {...} are allowed in Spring field bindings


For example:

// This works fine.
<input type="text" th:value="${object.covered} ? 'yes' : 'no'" />

// This on the other hand, generates the error mentioned earlier.
// Which does make sense, cause it would otherwise generate invalid attributes.
<input type="text" th:field="${object.covered} ? 'yes' : 'no'" />

// Combining the two does not work.
<input type="text" th:field="${object.covered}" th:value="${object.covered} ? 'yes' : 'no'" />

Basically, what I want, is to create a th:field where its value is determined by a conditional expression.

More specific, In my implementation I want to populate a input field with a number (Java long) from my model. And if that number is zero or lesss, I want to use a placeholder instead.

// Ultimateley, what I want to achieve is something like this.
<input type="text" th:field="${person.age}" 
       th:value="${person.age} le 0 ? null : ${person.age}" 
       placeholder="age" />

How to use th:field, and determine its value with a conditional expression with Spring Thymeleaf?

(Thymeleaf 2.1.5, and Spring Boot 1.4.2)

1

1 Answers

0
votes

Thymeleaf th:field generates 3 html attributes id, name an value.

For your case, instead of using th:field, use id, name and placeholder when age is less than zero, as shown below

<input th:if="${person.age > 0}" type="text" th:field="${person.age}" />
<input th:if="${person.age <= 0}" type="text" id="person.age" name="person.age" placeholder="age"/>