spring - 将 bean 字段传递给 :field in Thymeleaf fragment

标签 spring thymeleaf

我正在尝试重构具有大量复制粘贴的 Thymeleaf 代码。一般的想法是我们有这样的事情:

<form th:object="${createForm}">
  <div><input type="text" th:field="*{first}"/> <!-- some boilerplate code --></div>
  <div><input type="text" th:field="*{second}"/> <!-- some boilerplate code --></div>
  <div><input type="text" th:field="*{third}"/> <!-- some boilerplate code --></div>
  <div><input type="text" th:field="*{fourth}"/> <!-- some boilerplate code --></div>
 </form>

我想重构片段
  <input type="text" th:field="*{first}"/> <!-- some boilerplate code -->

到一个单独的文件,因为它是大量的复制粘贴(样板代码部分中有相当多的 HTML)。

我的第一种方法是做这样的事情:
<form th:object="${createForm}">
  <div th:replace="fragments/input :: input(*{first}" />
  <div th:replace="fragments/input :: input(*{second}" />
  <div th:replace="fragments/input :: input(*{third}" />
  <div th:replace="fragments/input :: input(*{fourth}" />
 </form>

然后有一个fragments/input.html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
</head>
<body>
<div th:fragment="input(field)">
    <input th:field="${field}"/> <!-- some boilerplate code -->
</div>
</body>
</html>

但是,一旦编译/部署,我得到错误
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'field' available as request attribute
有人知道如何解决这个问题吗?问题是减少代码复制粘贴,同时保留拥有 th:field 的好处。 .

我也试过使用 th:with像这样
<div th:width="field=*{first}" th:replace="fragments/smallslider :: input()" />

和片段
<div th:fragment="input()">
    <input th:field="${field}"/> <!-- some boilerplate code -->
</div>

但这既没有产生错误也没有生成 HTML。

最佳答案

我以与@Wilson 类似的方式解决了这个问题。

分段:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
    <div th:fragment="input(fieldName)">
        <input th:field="*{__${fieldName}__}" type="text">
    </div>
</body>
</html>

来电:
<form th:object="${createForm}">
    <div th:replace="fragments/input :: input('first')" />
    <div th:replace="fragments/input :: input('second')" />
    <div th:replace="fragments/input :: input('third')" />
    <div th:replace="fragments/input :: input('fourth')" />
</form>

关于spring - 将 bean 字段传递给 :field in Thymeleaf fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922575/

相关文章:

java - Thymeleaf:如何获取 URL 属性值

spring - 如何使用 Spring 捕获 Thymeleaf( View )渲染异常?

java - Spring Controller : Validation failed for object ='invoiceData' . 错误计数:4

sql-server - 当我添加 sql 脚本时,Spring Boot 不起作用

java - Spring Security + MVC : same @RequestMapping, 不同@Secured

java - Spring Data Jpa - ManyToMany - 删除连接表的实体

java - 如何在模板 Thymeleaf 中调用使用 Java (Spring) 创建的函数?

java - thymeleaf 是一种什么样的解决方案?

spring - 为什么我需要一个用于 Autowiring /注入(inject)字段的 setter ?

spring - 为什么 Autowiring bean 为空?