Thymeleaf 构造对象 [英] Thymeleaf construct object
问题描述
我将模型属性从控制器传递到百里香叶表单,以便我可以像这样绑定对象:
<form name="f" th:action="@{/signup}" th:object="${userCredentials}" method="post" class="form-horizontal"><input th:placeholder="#{messages.form.email}" type="text" th:field="*{email}"name="email" id="email" class="form-control"/><input th:placeholder="#{messages.form.name}" type="text" th:field="*{name}"name="name" id="name" class="form-control"/><input type="password" th:placeholder="#{messages.form.password}" th:field="*{password}"名称="密码" id="密码"/><button type="submit" th:text="#{messages.form.signup}"></button></表单>
但是我想将此表单作为来自其他视图的片段重用,但我不能这样做,因为 ${userCredentials}
表单对象未初始化.我可以像这样在我的视图中以某种方式构造这个对象吗?
<div th:if="${userCredentials == null}" th:with="userCredentials=new UserCredentials()"></div>
我认为使用 new
创建对象是不可能的,但是您可以在 UserCredentials 上创建一个返回一个静态方法的静态方法新对象并使用它.像这样:
public class UserCredentials {公共静态 UserCredentials create() {返回新的 UserCredentials();}}
在百里香叶中
<div th:if="${userCredentials == null}" th:with="userCredentials=${T(your.package.here.UserCredentials).create()}"><;/div>
Im passing a model attribute from controller to thymeleaf form so I could bind object like this:
<div class="container" style="max-width: 600px" th:fragment="signupForm">
<form name="f" th:action="@{/signup}" th:object="${userCredentials}" method="post" class="form-horizontal">
<input th:placeholder="#{messages.form.email}" type="text" th:field="*{email}"
name="email" id="email" class="form-control"/>
<input th:placeholder="#{messages.form.name}" type="text" th:field="*{name}"
name="name" id="name" class="form-control"/>
<input type="password" th:placeholder="#{messages.form.password}" th:field="*{password}"
name="password" id="password"/>
<button type="submit" th:text="#{messages.form.signup}"></button>
</form>
</div>
However I'd like to reuse this form as fragment from other views, but I can't do that because the ${userCredentials}
form object is not initialized. Can I somehow construct this object inside of my view like this?
<div th:if="${userCredentials == null}" th:with="userCredentials=new UserCredentials()"></div>
I don't think it's possible to create an object using new
, you can however create a static method on UserCredentials that returns a new object and use that. Something like this:
public class UserCredentials {
public static UserCredentials create() {
return new UserCredentials();
}
}
and in the thymeleaf
<div th:if="${userCredentials == null}" th:with="userCredentials=${T(your.package.here.UserCredentials).create()}"></div>
这篇关于Thymeleaf 构造对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!