【问题标题】:View helper for Spring Boot and Thymeleaf查看 Spring Boot 和 Thymeleaf 的帮助程序
【发布时间】:2018-05-01 18:41:52
【问题描述】:

我是 Spring Boot 新手,现在我们想使用 Spring Boot 2 和 Thymeleaf 3 作为模板引擎,用 Java 重写我们的旧 PHP 应用程序。

我们的旧版应用程序有数百个表单和数千个输入字段。为此,我们使用了一个简单的模板助手,它使得渲染输入字段、标签和容器 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>

如何在 Spring 和 Thymeleaf 中实现这一点?

【问题讨论】:

  • 是的,我们使用 Thymeleaf v3。

标签: spring spring-mvc spring-boot thymeleaf


【解决方案1】:

选项 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. 使用 spring bean 服务

Thymeleaf 允许使用 @beanName 语法 (more info) 访问在 Spring Application Context 中注册的 bean,例如:

<div th:text="${@formBuilder.addInputField('Close','close_time')}">...</div>

【讨论】:

  • 这两个选项都有效,谢谢!我认识到的另一件事是,似乎 th:replace 仅适用于片段,但不适用于 bean 服务。 bean 服务是否可以以 th:replace 之类的形式使用它?我的意思是消除输出中的支架元素?所以在上面的例子中,我不希望持有者 div 标签只是 bean 服务的输出。
  • @Vmxes 使用th:remove="tag" 消除持有人标签
  • 或者我认为,你可以使用thymeleaf.org/doc/tutorials/3.0/… [[${@formBuilder.addInputField('Close','close_time')}]] 不带任何标签
猜你喜欢
  • 2023-03-12
  • 2015-09-14
  • 1970-01-01
  • 2016-08-24
  • 2020-11-08
  • 2014-09-13
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多