【问题标题】:How can I create dynamic table in Thymeleaf..?如何在 Thymeleaf 中创建动态表..?
【发布时间】:2019-10-28 00:21:11
【问题描述】:

我是 Thymeleaf 的新手,正在尝试在 Themeleaf 模板上创建一个动态表格。

我该怎么做..??

我一直在谷歌搜索,但没有得到任何正确的答案。问题是我无法迭代 List>。我可以有任意数量的列,列名可以是任何东西。

<tr class="headings">
 <th class="column-title">ID</th>
 <th class="column-title">Name</th>
 <th class="column-title">Salary</th>
 <th class="column-title">Status</th>  
 </tr>
</thead>
<tbody>
 <tr class="even pointer" th:each="row:${rows}" id = "tablerow">
 <td class=" " th:text="${row.getId()}">Id</td>
 <td class=" " th:text="${row.getName()}">Name</td>
 <td class=" " th:utext="${row.getSalary()}">Salary</td>
 <td class=" " th:text="${row.getStatus()}">Active</td>
 </tr>
</tbody>

我需要动态设置值,因为如果查询结果会不断变化。现在列名是硬编码的,并且值也通过 row.getId 得到如果没有 Id,它可能是行中的任何东西我应该使用什么而不是..?示例行。。 rows 作为 List> 获得。

提前致谢。

【问题讨论】:

    标签: spring-boot model-view-controller thymeleaf


    【解决方案1】:

    您可以像迭代 List 一样轻松地迭代 Map。最简单的形式是:

    <tbody>
        <tr class="even pointer" th:each="row: ${rows}" id="tablerow">
            <td th:each="field: ${row}" th:text="${field.value}" />
        </tr>
    </tbody>
    

    但是,由于Maps 没有特定的顺序(除非您使用类似TreeMap 的东西),我会这样做(完整示例应与您的示例表匹配) :

    控制器

    List<String> headers = Arrays.asList("ID", "Name", "Salary", "Status");
    List<Map<String, Object>> rows = new ArrayList<>();
    rows.add(Map.of("ID", "1", "Name", "Jim", "Salary", "50000", "Status", "active"));
    rows.add(Map.of("ID", "2", "Name", "Sally", "Salary", "50000", "Status", "inactive"));
    

    模板

    <table>
        <thead>
            <tr class="headings">
                <th th:each="header: ${headers}" class="column-title" th:text="${header}" />
            </tr>
        </thead>
    
        <tbody>
            <tr class="even pointer" th:each="row: ${rows}" id="tablerow">
                <td th:each="header: ${headers}" th:text="${row.get(header)}" />
            </tr>
        </tbody>
    </table>
    

    这将产生:

    <table>
        <thead>
            <tr class="headings">
                <th class="column-title" >ID</th>
                <th class="column-title" >Name</th>
                <th class="column-title" >Salary</th>
                <th class="column-title" >Status</th>
            </tr>
        </thead>
    
        <tbody>
            <tr class="even pointer" id="tablerow">
                <td >1</td>
                <td >Jim</td>
                <td >50000</td>
                <td >active</td>
            </tr>
            <tr class="even pointer" id="tablerow">
                <td >2</td>
                <td >Sally</td>
                <td >50000</td>
                <td >inactive</td>
            </tr>
        </tbody>
    </table>
    

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 2015-04-19
      • 1970-01-01
      • 2018-07-30
      • 2017-11-28
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      相关资源
      最近更新 更多