2017-11-17 255 views
1

我是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實現這一目標?

+0

是的,我們使用Thymeleaf V3。 – Vmxes

回答

2

選項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> 
+0

這兩個選項的作品,謝謝! 我還認識到另外一件事情,它看起來像是:替換隻能與碎片一起工作,而不能與bean服務一起工作。 bean服務可以像th這樣的形式使用它:replace?我的意思是消除輸出中的支架元件?所以在上面的例子中,我不希望持有者div標記bean服務的輸出。 – Vmxes

+0

@Vmxes使用'th:remove =「tag」'來消除持有者標籤 – varren

+0

或者我認爲,您可以使用http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-inlining' [[$ {@ formBuilder.addInputField('Close','close_time')}]]'沒有任何標籤 – varren