【问题标题】:Using a form to display model objects in Thymeleaf. Is there a better way to do this?使用表单在 Thymeleaf 中显示模型对象。有一个更好的方法吗?
【发布时间】:2021-11-20 23:44:47
【问题描述】:

一直在努力适应 Spring Boot/Thymeleaf/前端开发。我目前在前端使用一个表格来显示来自后端的对象列表,以及一个允许用户查看列表中每个项目的属性的表单。

我觉得我这样做的方式真的很奇怪,并且觉得可能有更好的方法。非常感谢任何提示/反馈,谢谢。

HTML/百里香

<!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>

控制器

@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";
}

输出(需要 10 个代表发布图片,所以这是一个链接)

【问题讨论】:

    标签: java html spring-boot thymeleaf


    【解决方案1】:

    一个潜在的改进/简化是删除表单并用锚点替换输入。锚看起来像这样(未经测试!):

    <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>
    

    您可以根据需要设置 selectedButton 和 deselectedButton 的样式。

    【讨论】:

    • 哇,非常感谢 :) 这正是我正在寻找的解决方案类型。
    • 上述解决方案可以工作,但要完全兼容 HTML,您需要删除按钮标签,将 th:text 添加到锚点,并使用 th:classappend 将锚点设置为按钮。
    • 为什么按钮不被认为是 HTML 兼容的?
    • 根据 HTML 规范,锚点不能有交互式后代。按钮是交互式的。
    猜你喜欢
    • 2014-08-22
    • 2016-09-12
    • 2013-05-03
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    相关资源
    最近更新 更多