我正在尝试重构具有大量复制粘贴的 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/