我有一个扩展了BaseEntity超类的Author类。在模板中,我试图从作者变量中获得布尔属性,以便我可以重用创建和更新表单。
谁能解释一下我做错了什么原因,我在哪里可以读到更多?我在文档中尝试了大多数/所有EL方式来访问该字段,所以我猜它是在类中,因为将布尔属性添加到Author类本身是有效的。
BaseEntity
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private boolean isNew;
public boolean isNew() {
return this.id == null;
}
模板
<div class="container">
<form th:object="${author}" method="post">
<div class="form-row">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" class="form-control" th:field="*{firstName}" placeholder="...">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" class="form-control" th:field="*{lastName}" placeholder="...">
</div>
</div>
**<button th:text="${author['isNew']} ? 'Create New Author' : 'Update Author'" type="submit" class="btn btn-primary" >Process</button>**
</form>
</div>
表达式I've try
<button th:text="${author['isNew']} ? 'Create New Author' : 'Update Author'" type="submit" class="btn btn-primary" >Process</button>
<button th:text="${author['isNew']} == true ? 'Create New Author' : 'Update Author'" type="submit" class="btn btn-primary" >Process</button>
<button th:text="${author['new']} ? 'Create New Author' : 'Update Author'" type="submit" class="btn btn-primary" >Process</button>
<button th:text="${author['new']} == true ? 'Create New Author' : 'Update Author'" type="submit" class="btn btn-primary" >Process</button>
<button th:text="${author.isNew()} ? 'Create New Author' : 'Update Author'" type="submit" class="btn btn-primary" >Process</button>
<button th:text="${author.isNew} == true ? 'Create New Author' : 'Update Author'" type="submit" class="btn btn-primary" >Process</button>
<button th:with="text=${author['new']} ? 'Create New Author' : 'Update Author'" th:text="${text}" type="submit" class="btn btn-primary" >Process</button>
我修改了更多的EL表达式,得到了下面这些结果。这对我来说可能意味着thymeleaf没有正确处理boolid == null
的三元运算符。
<button th:with="text=${author.id} > 0" th:text="${text}" type="submit" class="btn btn-primary" >Process</button> //true
<button th:with="text=${author.id} == null" th:text="${text}" type="submit" class="btn btn-primary" >Process</button> //false
工作的表达式不涉及读取字段,使其冗余:
<button th:with="text=${author.id} == null" th:text="${text} ? 'Create New Author' : 'Update Author'" type="submit" class="btn btn-primary" >Process</button>
如果你知道一个解决方案,请PM/评论!其工作的示例项目是:https://github.com/spring-projects/spring-petclinic/blob/main/src/main/java/org/springframework/samples/petclinic/model/BaseEntity.java
您需要将所有内容放入${}中以让百里香叶子理解表达式
<button th:text="${author.isNew() ? 'Create New Author' : 'Update Author'}" type="submit" class="btn btn-primary" >Process</button>