如何在 Thymeleaf 中创建动态表..?

Raj*_*Raj 4 model-view-controller thymeleaf spring-boot

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

我该怎么做..??

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

<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>
Run Code Online (Sandbox Code Playgroud)

我需要动态设置值,因为结果查询是否会不断变化。现在列名是硬编码的,值也是通过row.getId获取的,如果没有 Id,它可以是行中的任何内容,我应该使用什么比..?示例行。<>。rows 通过 List<Map<String, Object>> 获得。

提前致谢。

Met*_*ids 6

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

<tbody>
    <tr class="even pointer" th:each="row: ${rows}" id="tablerow">
        <td th:each="field: ${row}" th:text="${field.value}" />
    </tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)

但是,由于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"));
Run Code Online (Sandbox Code Playgroud)

模板

<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>
Run Code Online (Sandbox Code Playgroud)

这将产生:

<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>
Run Code Online (Sandbox Code Playgroud)