Spring Thymeleaf - th:field中的条件表达式

时间:2016-11-23 03:28:34

标签: spring thymeleaf

Conditional Expression (docs):

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

我想在th:字段中使用条件表达式。但每次我尝试它时都会出现以下错误:

  

* Spring字段绑定中只允许使用变量表达式$ {...}或选择表达式 {...}

例如:

// 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'" />

基本上,我想要的是创建一个th:字段,其值由条件表达式决定。

更具体地说,在我的实现中,我想用我的模型填充一个带有数字(Java long)的输入字段。如果该数字为零或更少,我想改为使用占位符。

// 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" />

如何使用th:field,并使用Spring Thymeleaf的条件表达式确定其值?

(Thymeleaf 2.1.5和Spring Boot 1.4.2)

1 个答案:

答案 0 :(得分:0)

Thymeleaf th:field生成3个html属性idnamevalue

对于您的情况,当年龄小于零时,请使用th:fieldidname,而不是使用placeholder,如下所示

<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"/>