【问题标题】:How to use Thymeleaf's #lists.isEmpty with Spring Data's Page interface?如何将 Thymeleaf #lists.isEmpty 与 Spring Data Page 接口一起使用?
【发布时间】:2017-04-22 12:50:29
【问题描述】:

我使用 jpenren 的 Thymeleaf Spring Data Dialect:https://github.com/jpenren/thymeleaf-spring-data-dialect

听从他最后的建议:

默认情况下 SpringDataDialect 在请求中搜索属性 “页面”或者如果一个类型的属性 org.springframework.data.domain.Page 存在。使用其他模型 属性,使用 sd:​​page-object="${attrName}"

我在我的 Spring 控制器中做了这样的事情:

@RequestMapping("search")
public String search(Model model, @PageableDefault Pageable pageable) {
    Page<User> users = userRepository.findAll(pageable);
    model.addAttribute("users", users);
    return "user/search";
}

在我的search.html 视图中,摘录如下:

    <table class="table">
      <caption class="text-xs-center" th:if="${#lists.isEmpty(users)}">No user found</caption>
      <thead>
        <tr>
          <th>Username</th>

            (...)

      <tbody>
        <tr th:each="user : ${users}">
          <td th:text="${user.name}">Username</td>

很遗憾,${#lists.isEmpty(users)} 不起作用。它适用于我不使用此 Page&lt;?&gt; 的其他页面。

那么我该如何做这个测试呢?

【问题讨论】:

  • 我不确定我是否得到了连接。您首先参考 Spring Data Thymeleaf 方言,然后不要使用它。示例代码还显示了列表表达式中使用的不同变量,而不是 users。页面有一个getContent() 方法返回一个List,因此将page.content 交给列表表达式应​​该可以解决问题。
  • 我使用了分页,但它没有带来任何东西,因为它只是像&lt;nav&gt;&lt;ul sd:pagination="compact-pager"&gt;&lt;/ul&gt;&lt;/nav&gt; 这样的一些想法我还修复了代码,正确的变量确实是users
  • 如您所说,使用 getContent() 很有用:我成功使用了th:if="${#lists.isEmpty(users.content)}"
  • 最后我选择了...th:unless="${adherents.hasContent()}"
  • 酷,我把它变成了一个参考答案。

标签: spring-mvc pagination spring-data thymeleaf


【解决方案1】:

看起来 Thymeleaf 的 #lists 真的期望 ListPage 显然不是因为它只实现了 Iterable。列表内容可以参考page.content

由于您首先要检查内容的存在(或不存在),因此您可以直接使用 Page.hasContent(),这意味着 th:unless="{adherents.hasContent()} 也应该可以解决问题。

【讨论】:

  • 您介意编辑您的答案并使用users 作为变量名吗?请注意,我也无法编辑我上面的最后一条评论......你可以吗?
  • 结果:Could not parse as expression: "{posts.hasContent()}"
猜你喜欢
  • 2014-08-16
  • 2019-06-20
  • 2012-05-10
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 2014-03-10
  • 2017-07-29
  • 1970-01-01
相关资源
最近更新 更多