首页 > 解决方案 > 如何打印出在 Thymeleaf 中按字母分组的列表中的元素?

问题描述

我有以下数据库表:

CREATE TABLE authors
    (
        id         INT AUTO_INCREMENT PRIMARY KEY,
        authorName VARCHAR(250) NOT NULL
    );

我想按如下方式打印我们的作者:

一个

C

D

目前我通过thymleaf模板打印如下,不想每次都在作者面前打印出Alphabet LETTER:

一个

C

C

D

D

D

我的控制器:

@GetMapping("/index.html")
    public String mainPage(Model model) {
        model.addAttribute("authorsData", bookService.getAuthorData());
        return "/authors/index";
    }

我的服务:

public List<Author> getAuthorData() {
    List<Author> authors = jdbcTemplate.query("SELECT id, authorName from authors ORDER BY authorName", (ResultSet rs, int rowNum) -> {
        Author author = new Author();
        author.setId(rs.getInt("id"));
        author.setAuthorName(rs.getString("authorName"));
        return author;
    });
    return new ArrayList<>(authors);
}

我的百里香代码如下:

<div class="Authors-block" th:each="author : ${authorsData}" >
  <h2 class="Authors-title" id="a" th:text="${author.getAuthorName().charAt(0)}">
  </h2>
  <div class="Authors-letter">
    <div class="Authors-item"><a href="/authors/slug.html" th:text="${author.getAuthorName()}"></a>
    </div>

标签: spring-bootthymeleaf

解决方案


让您的 getAuthorData() 返回 Map<Character, List> 其中键是字母,值是作者以该字母开头

public List<Author> getAuthorData() {
    List<Author> authors = jdbcTemplate.query("SELECT id, authorName from authors ORDER BY 
    authorName", (ResultSet rs, int rowNum) -> {
        Author author = new Author();
        author.setId(rs.getInt("id"));
        author.setAuthorName(rs.getString("authorName"));
        return author;
    });
    return authors.stream()
       .collect(
          Collectors.groupingBy(
             author -> author.getAuthorName().charAt(0)
          )
       );
}

在 html 中,您可以遍历地图条目,如下所示:How to loop through Map in Thymeleaf 只需注意作为一个值,您将拥有可迭代数组


推荐阅读