Spring Boot和Thymeleaf的查看帮助器
我是Spring Boot中的新成员,现在我们想用Spring Boot 2和Thymeleaf 3作为模板引擎重写Java中的旧PHP应用程序。Spring Boot和Thymeleaf的查看帮助器
我们的传统应用程序拥有数百个包含数千个输入字段的表单。为此,我们使用一个简单的模板助手,使得输入字段,标签和容器div非常简单。一个小例子:
FormBuilder::addInputField("Close","close_time",$data->getClose_time());
生成:
<tr>
<th>Close:</th>
<td><input type="text" name="close_time" id="close_time_id" size="30" value=""> </td>
</tr>
我怎么能在春天和Thymeleaf实现这一目标?
选项1.使用Thymeleaf片段
formBuilder.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<tr th:fragment="inputField (title, name, value)">
<th th:text="${title}"> or can use [[${title}]]</th>
<td><input type="text" th:name="${name}"
id="close_time_id" size="30" th:value="${value}"> </td>
</tr>
</body>
</html>
,然后在主布局可以使用
<body>
<table>
<tbody>
<tr th:replace="formBuilder::inputField ('Close','close_time', ${value})"></tr>
</tbody>
</table>
</body>
选项2.使用春豆服务
Thymeleaf允许访问在与@beanName语法(more info)的Spring应用上下文注册的bean,例如:
<div th:text="${@formBuilder.addInputField('Close','close_time')}">...</div>
这两个选项的作品,谢谢! 我还认识到另外一件事情,它看起来像是:替换只能与碎片一起工作,而不能与bean服务一起工作。 bean服务可以像th这样的形式使用它:replace?我的意思是消除输出中的支架元件?所以在上面的例子中,我不希望持有者div标记bean服务的输出。 – Vmxes
@Vmxes使用'th:remove =“tag”'来消除持有者标签 – varren
或者我认为,您可以使用http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-inlining' [[$ {@ formBuilder.addInputField('Close','close_time')}]]'没有任何标签 – varren
是的,我们使用Thymeleaf V3。 – Vmxes