1
votes

I'm new in Spring Boot and now we want to rewrite our old PHP application in Java using Spring Boot 2 and Thymeleaf 3 as template engine.

Our legacy app has hundreds of forms with thousands of input fields. For this we use a simple template helper that makes it quite simple to render the input fields, labels and container divs. A small example:

FormBuilder::addInputField("Close","close_time",$data->getClose_time());

Generates:

<tr>
    <th>Close:</th>
    <td><input type="text" name="close_time" id="close_time_id" size="30" value=""> </td>
</tr>

How can I achieve this in Spring and Thymeleaf?

1
Yes, we use Thymeleaf v3.Vmxes

1 Answers

2
votes

Option 1. Use Thymeleaf fragments

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>

and then in your main layout you can use

<body>
<table>
    <tbody>
    <tr th:replace="formBuilder::inputField ('Close','close_time', ${value})"></tr>
    </tbody>
</table>
</body>

Option 2. Use spring bean service

Thymeleaf allows accessing beans registered at the Spring Application Context with the @beanName syntax (more info), for example:

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