【问题标题】:How to access a list property of an object using thymleaf如何使用 thymeleaf 访问对象的列表属性
【发布时间】:2020-12-15 19:30:58
【问题描述】:

如何使用 Thymleaf 访问 HTML 中对象中包含的列表变量

例如:aClient 的所有属性都是 String 对象。它们可以被访问为

<tr th:each="aClient : ${clientList}">
 <td th:text="${aClient.firstName}"/>
 <td th:text="${aClient.lastName}"/>
 <td th:text="${aClient.address}"/>
 <td th:text="${aClient.clientType}"/>

但是对于像这样的财产

List&lt;Service&gt; services.

如何访问它?

在阅读后尝试在下面做。但它没有提取服务的名称。

<div th:each="service, serv : *{services}">
<input type="text" th:field="*{service[__${serv.index}__].name}" />
</div>

“name”是Service类中带有getter和setter的属性。

【问题讨论】:

    标签: spring spring-boot thymeleaf


    【解决方案1】:

    输入字段的内容由value 属性标识。

    此外,您不需要使用 Thymeleaf serv 迭代器跟踪器,因为在这种情况下,您已经在迭代每个 Service 对象 - 您只想获取每个对象的 name 字段的值.

    这都可以简化为:

    <div th:each="service : ${services}">
        <input type="text" th:value="${service.name}" />
    </div>
    

    (这与您用于 th:text 数据的方法基本相同。)

    生成的HTML如下:

    <div>
        <input type="text" value="service 1 name">
    </div>
    <div>
        <input type="text" value="service 2 name">
    </div>
    

    这假设您希望每个输入字段都在自己的 div 中。

    【讨论】:

      【解决方案2】:

      需要在列中插入服务名称。这是通过

      实现的
      <td>
          <div th:each="service : ${aClient.services}" th:text="${service.name}"></div> 
      </td>
      

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 2012-11-22
        • 1970-01-01
        • 1970-01-01
        • 2020-07-31
        • 1970-01-01
        • 1970-01-01
        • 2017-02-13
        相关资源
        最近更新 更多