Home > Software engineering >  Using a form to display model objects in Thymeleaf. Is there a better way to do this?
Using a form to display model objects in Thymeleaf. Is there a better way to do this?

Time:09-30

been trying to get comfortable with Spring Boot/Thymeleaf/frontend development in general. I'm currently using a table on the frontend to display a list of objects from the backend, as well as a form to allow users to view properties of each item in the list.

I feel like the way I'm doing this is really weird and feel that there could be a better way. Would appreciate any tips/feedback, thank you.

HTML/Thymeleaf

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Gambler Card List</title>
    <link th:href="@{/css/styles.css}" rel="stylesheet" />
</head>
<body>
    <h1>Gambler Card List</h1>

    <div class="cardlist-wrapper">
        <div class="cardlist-names">
            <form action="/gambler/cardlist" method="get">
                <table class="cardlist-table">
                    <tr th:each="card : ${cardList.getCardList()}">
                        <td>
                            <input th:class="card-btn"
                                   th:attr="id=${{card.getId()} == {currentCard.getId()} ? 'selected' : ''}"
                                   type="submit" th:value="${card.getName()}" name="cardName">
                        </td>
                    </tr>
                </table>
            </form>
        </div>

        <div class="cardlist-description">
            <h4 th:text="${currentCard.getDescriptionTitle()}"></h4>
            <p th:text="${currentCard.getDescription()}"></p>
        </div>
    </div>
</body>
</html>

Controller

@RequestMapping(value = "gambler/cardlist")
public String baseCardList(Model model, 
                           @RequestParam(value="cardName", required=false) String cardName) {

    model.addAttribute("currentCard", cardList.getCardByName(cardName));
    model.addAttribute("cardList", cardList);
    return "gambler/cardlist";
}

Output (need 10 rep to post image, so here's a link)

output

CodePudding user response:

One potential improvement/simplification is to remove the form and replace the inputs with anchors. The anchors would look something like this (not tested!):

<a th:href="@{/gambler/cardlist(cardName=${card.name})}">
  <button th:text="${card.name}"
    th:classappend="${card.id == currentCard.id ? 'selectedButton' : 'deselectedButton'}">Card Name</button>
</a>

You can style selectedButton and deselectedButton as you wish.

  • Related