0

I have a simple one-page web application and Im using Thymeleaf to try and display a table that can handle different lists of objects being passed to it.

For example, it should be able to handle List<County> where County looks like:

public class County {
     String name;
     String district;
     LocalDate date;
     int cases;
}

But it also needs to be able to handle List<State> where State looks like:

public class State {
     String name;
     int latitude;
     int longitude;
     LocalDate date;
}

What I have come up with so far is something like:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

    <table border="1" cellpadding="10" >
        <tr> 
            <th>Col 2</th>
            <th>Col 3</th>
            <th>Col 4</th>
            <th>Col 5</th>
        </tr>
        <tr th:each="county: ${countyList}">
            <td th:text="${county.name}"></td>
            <td th:text="${county.district}"></td>
            <td th:text="${county.date}"></td>
            <td th:text="${county.cases}"></td>

        </tr>
      </table>
</body>
</html>

But this only handles one type of object with a certain number of columns. I am wondering how I can dynamically make this table so it has how every many fields the object that is passed to it has, and how to make this table handle whichever object is passed.

Is this something that can be done, if not, how should I redesign this so that I can still have one table on the page

Thanks!

1
  • 1
    You are probably looking for something like fragments. Commented Jun 3, 2020 at 22:23

1 Answer 1

2

You can use th:if for this. It would be difficult and not correct to discover in the templating engine the structure of the data so just use purpose-based blocks like so:

<div th:if="${countyList != null}">
    <table border="1" cellpadding="10">...</table>
</div>
<div th:if="${stateList != null}">
    <table border="1" cellpadding="10">...</table>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.