【问题标题】:How iterate by one after another in Thymeleaf- Spring - Boot?Thymeleaf-Spring-Boot中如何一个接一个地迭代?
【发布时间】:2021-03-14 18:30:24
【问题描述】:

我们如何在 Thymeleaf 页面上迭代列表?假设我有一个包含一个对象的列表

我可以在 Thymeleaf 页面上依次显示所有用户信息,但这实际上是我不想实现的。有什么方法可以让我一次显示一个用户,下一个按钮上会有两个按钮单击移动到下一个可用用户并显示信息并隐藏以前的用户信息,当单击上一个按钮时移回前一个。因为我有超过 20+ 甚至有时 50+ 的用户信息。

public class Info {
private String name;
private String dob;
private String university;
// constructor , getter and setter
}

我的控制器类

@GetMapping("/get/All-user-info")
public String getAllUserInfo(Model model){
  List<Info> info = new ArrayList<>();
info.add(new Info("NA","22/02/2020","Florida"));
info.add(new Info("PA","22/01/2020","Florida"));
info.add(new Info("CA","22/03/2020","Florida"));
info.add(new Info("DA","22/04/2020","Florida"));
model.addAttribute("info",info);
return "page-thyme";
}

我的 Thymeleaf 页面看起来像。它一口气显示所有内容。我真的不明白在这里做什么。

<div th:each="info, status : ${info}">
<p th:text="${info.name}">
<p th:text="${info.dob}">
<p th:text="${info.university}">
</div>

编辑: 我添加了一个服务类

@GetMapping("/get/All-user-info/{departmentId}")
public String getAllUserInfo(Model model, @PathVariable String departmentId){
  List<Info> info = userService.getUser(departmentId);
model.addAttribute("info",info);
return "page-thyme";
}

【问题讨论】:

  • 我不认为这是一个 Thymeleaf 问题,本身 - 我认为这更像是一个 “如何在 Spring Boot 中实现分页? 问题。Thymeleaf 可以支持分页解决方案,但不提供这样的解决方案。我认为研究“Spring Boot 分页”可能是一个不错的起点。

标签: javascript java spring-boot thymeleaf


【解决方案1】:

您可以像这样在控制器的参数中传递对象的索引:

@GetMapping (path = "/modal")
public String modal(Model model, @RequestParam(name = "page", defaultValue = "0") int page) {
    List<Info> info = new ArrayList<>();
    
    info.add(new Info("NA","22/02/2020","Florida"));
    info.add(new Info("PA","22/01/2020","Florida"));
    info.add(new Info("CA","22/03/2020","Florida"));
    info.add(new Info("DA","22/04/2020","Florida"));
    model.addAttribute("info",info);
    model.addAttribute("index",page);
    return "modal";
}

并在您的 HTML 页面中添加一种分页:

<div >
  <p th:text="${info[__${index}__].name}">
  <p th:text="${info[__${index}__].dob}">
  <p th:text="${info[__${index}__].university}">
  <div th:each="info, status : ${info}"><a th:text="${status.index}" th:href="@{modal(page=${status.index})}"></a></div>
</div>

【讨论】:

  • thankyou Xtof,但我确实有一个问题,假设我有 info 列表,它将来自已部署的 rest API,所以每次它必须与其 API 交互时,我认为这是不对的接近你所说的?你能解释一下[__${x}__] 是什么意思吗,因为我对它很陌生。
  • 嗨@Xtof,我刚刚对问题进行了额外的更改,请查看是否可以提供帮助。有没有一种方法可以一次性使用整个列表并仅在 Thymeleaf 上进行迭代
  • @AyushKangar - __${x}__ 是 Thymeleaf 的 pre-processing syntax。
  • @AyushKangar - 您评论说:每次它必须与其 API 交互时 - 是的,它必须这样做。 Thymeleaf 无法单独处理客户端用户触发的分页。它不是那种类型的工具。好消息是:您使用的是 Spring,而 Spring 提供了分页支持。
  • 嗨@AyushKangar,您的问题已由andrewjames 完成。如果您想在 Spring 中使用分页,只需附加注释:您在控制器中返回的类型将是 Page 而不是 List。做一些测试并在需要时提出一个新问题,否则它将成为问题中的问题......
猜你喜欢
  • 2016-05-14
  • 2018-11-26
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 2020-02-20
  • 2014-11-07
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多