Thymeleaf构造对象

时间:2016-11-28 10:56:33

标签: java spring thymeleaf

我将一个模型属性从控制器传递给百日咳形式,所以我可以像这样绑定对象:

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

但是我想将此表单作为其他视图的片段重用,但我不能这样做,因为${userCredentials}表单对象未初始化。我能以某种方式在我的视图中构建这个对象吗?

<div th:if="${userCredentials == null}" th:with="userCredentials=new UserCredentials()"></div>

2 个答案:

答案 0 :(得分:1)

您可以使用

th:with中创建对象
th:with="userCredentials=${new UserCredentials()}"

答案 1 :(得分:0)

我不认为使用new创建对象是可能的,但是您可以在UserCredentials上创建一个静态方法,该方法返回一个新对象并使用它。像这样:

public class UserCredentials {
  public static UserCredentials create() {
    return new UserCredentials();
  }
}

并在百里香中

<div th:if="${userCredentials == null}" th:with="userCredentials=${T(your.package.here.UserCredentials).create()}"></div>