我正在尝试重构具有大量复制粘贴功能的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。
答案 0 :(得分:3)
你可以通过将bean字段的名称传递给片段来实现这一点。
(defun x-mode-reformat-region (beg end)
"..."
(interactive "r")
(save-restriction
(widen)
(save-excursion
(setq beg (progn (goto-char beg) (line-beginning-position))
end (progn (goto-char end) (line-end-position)))
(narrow-to-region beg end)
(goto-char (point-min))
(while (not (eobp))
(insert "*") ;; placeholder for fancy reformatting
(forward-line)))))
并称之为
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
</head>
<body>
<div th:fragment="input(fieldName, fieldValue)">
<input th:name="${fieldName}" th:value=${fieldValue}/> <!-- some boilerplate code -->
</div>
</body>
</html>
答案 1 :(得分:0)
我以与@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>