2015-06-22 54 views
0

是否可以使用Thymeleaf動態地構建表格?用Thymeleaf動態構建表格

基本上我希望能夠傳遞任何對象,表格將顯示錶示對象中字段數量的列數。

例如

對象1

  • 第一名稱

  • DOB

對象2

  • 代碼

  • 街道

  • 城市

時傳遞給此相同thymleaf表會產生不同的結果:

對象1個表:

<tr> 
<td>First Name</td> 
<td>Last Name</td> 
<td>DOB</td> 
</tr> 

對象2表:

<tr> 
<td>Number</td> 
<td>Code</td> 
<td>Street</td> 
<td>City</td> 
</tr> 

回答

2

概念和背景

這篇文章會給你如何獲取一個類的屬性的想法,並得到這些屬性的值使用org.apache.commons.beanutils.PropertyUtils

https://stackoverflow.com/a/13960004/1251350


實施意見

建立與方法的bean來使用上述方法得到傳遞對象的屬性的map<String, Object>

@Service("objService") 
class ObjectService { 
    public Map<String, Object> convertToArray(Object object){ 
     // the logic to be taken from 
     // https://stackoverflow.com/a/13960004/1251350 
    } 
} 

然後在thymeleaf模板得到的fragment argument傳遞的對象和迭代地圖http://forum.thymeleaf.org/How-to-iterate-HashMap-td3621264.html

<div th:fragment="objDisplay(obj)"> 
    <div th:each="entry : @objService.convertToArray(obj)"> 
     <!-- Thymeleaf template to display Map --> 
     <!-- http://forum.thymeleaf.org/How-to-iterate-HashMap-td3621264.html --> 
    </div> 
</div> 

我沒有把爲你寫的代碼的努力,爲我相信你可以在這個指導下自己做。乾杯!

+0

謝謝,終於有機會對此進行測試了。除非您傳遞的數據具有延遲初始化字段的對象,否則可以正常工作。你知道如何檢查字段是否被惰性初始化? – Aeseir