【问题标题】:How do I display data into two column with Thymeleaf and HTML?如何使用 Thymeleaf 和 HTML 将数据显示到两列?
【发布时间】:2022-01-15 08:39:43
【问题描述】:

我一直在左右搜索,但仍然找不到一个好的解决方案。另外我对编程很陌生,所以请原谅我描述事物的方式:)。我正在使用 Spring、MySQL、Java、Thymeleaf。

基本上,我有一个从控制器传递的对象列表:

[人 [code=1, name=A, car=ford1],person [id=2, name=A, car=ford2], person [id=1, name=B, car=toyota1], 人[id=2, name=B, car=toyota2] ]

我想在 HTML 表格或引导网格系统中使用 Thymeleaf 显示这些数据。

这是我得到的:

<div>
    <table
      class="
        table table-bordered table-striped table-hover table-responsive-xl
      "
    >
      <thead class="thead-dark">
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Car</th>
           <th>Name</th>
          <th>Car</th>
        </tr>
      </thead>
      <tbody>
        <tr th:each="person :${listOfPerson}">
          <td>
            [[${person.id}]]
          </td>
          <td>
            [[${person.name}]]
          </td>
          <td>
            [[${person.car}]]
          </td>
        </tr>
      </tbody>
    </table>
  </div>

所以这样显示数据:

ID Name Car Name Car
1 A ford1
2 A ford2
1 B toyota1
2 B toyota2

但我希望它显示如下:

ID Name Car Name Car
1 A ford1 B toyota1
2 A ford2 B toyota2

我想我可能需要以某种方式将此数据拆分为 id 1 和 id 2。以下是我可以想到的两种方法:

  • 使用 Thymeleaf th:if="${person.id.equals(1)} 获取 id 1 的数据,然后重复 2,我只是不知道如何将其放入表中。李>
  • 使用查询格式化数据,如果不使用 GROUP_CONCAT 将结果转换为单列,我不确定如何执行此操作。

也许我需要更改SQL表,请给我一些建议。

编辑:所以我想我找到了这个MySQL pivot的答案

【问题讨论】:

    标签: java html mysql spring thymeleaf


    【解决方案1】:

    按 id 对您的人员列表进行分组。假设您有一个这样的列表:

    List<Person> persons = Arrays.asList(
        new Person(1, "A", "ford1"),
        new Person(2, "A", "ford2"),
        new Person(1, "B", "toyota1"),
        new Person(2, "B", "toyota2")
    )
    

    分组:

    Map<Integer, List<Person>> groupedByIdPersons = persons.stream().collect(Collectors.groupingBy(Person::getId));
    

    在 Thymeleaf 中使用它:

    1. 遍历th:block 中的整个地图以创建标题。重复次数与按 id 分组的集合一样多。

    2. 遍历整个地图以提取键/值,然后仅遍历 th:block 中的值

    <thead>
        <tr>
            <th:block th:each="elem : ${groupedByIdPersons}">
                <th>ID</th>
                <th>Name</th>
                <th>Car</th>
            </th:block>
        </tr>
    </thead>
    <tbody>
        <tr th:each="elem : ${groupedByIdPersons}">
            <th:block th:each="person : ${elem.value}">
                <td>${person.id}</td>
                <td>${person.name}</td>
                <td>${person.car}</td>
            </th:block>
        </tr>
    </tbody>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      相关资源
      最近更新 更多