0

Is it possible to build a table dynamically using Thymeleaf?

Essentially what i hope to achieve is ability to pass any object and the table would show the number of columns representing number of fields in object.

e.g.

Object 1

  • first name

  • last name

  • DOB

Object 2

  • number

  • code

  • street

  • city

when passed to this same thymleaf table it would generate different results:

Object 1 Table:

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

Object 2 Table:

<tr>
<td>Number</td>
<td>Code</td>
<td>Street</td>
<td>City</td>
</tr>
Aeseir
  • 7,754
  • 10
  • 58
  • 107

1 Answers1

2

Concept and the background

This post will give you an idea of how to fetch the properties of a class and get the values of those properties using org.apache.commons.beanutils.PropertyUtils

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


Implementation Suggestion

Build a bean with the method to use the above methodology to get a map<String, Object> of properties of a passed object.

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

Then in the thymeleaf template get the object passed as a fragment argument and iterate the map 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>

I didn't put the effort to write the code for you, as I believe you can do it youself on this guidance. Cheers!

Community
  • 1
  • 1
Faraj Farook
  • 14,385
  • 16
  • 71
  • 97
  • Thanks, finally had chance to test this out. Works well unless you pass an object with data that has fields lazy initialized. Do you know how to check if field is lazy initialized? – Aeseir Jun 28 '15 at 12:00