【问题标题】:Thymeleaf map syntax causes TemplateProcessingExceptionThymeleaf 映射语法导致 TemplateProcessingException
【发布时间】:2017-10-09 15:02:49
【问题描述】:

我正在尝试构建一个包含用户网格及其权限的页面。该项目是一个 Spring MVC Boot + Thymeleaf 项目。版本:

  1. 百里香 3.0.3
  2. Thymeleaf 布局方言 2.2.1
  3. Spring Boot 1.5.2 (注意我必须覆盖 Spring Boot 的 Thymeleaf 版本,因为 Layout Dialect 版本非常过时。)

每个用户都有一个办公室和多个角色。 RoleDescription、Office 和 User 是包含许多字符串的 POJO。我像这样在控制器中填写我的数据。

  @RequestMapping("/admin/users")
  public String userGrid(Model model) {
      MyWebServiceClient myClient = clientFactory.getClient();
      List<RoleDescription> roles = myClient.getRoleList();
      Map<String, Office> offices = myClient.getOfficeMap();
      List<User> users = myClient.getUserRoleGrid();
      model.addAttribute("offices", offices);
      model.addAttribute("roles", roles);
      model.addAttribute("users", users);
      return "usergrid";
  }

然后我在我的 Thymeleaf 模板页面中显示数据,如下所示:

        <tbody th:each="user: ${users}" th:with="officeId=${user.officeId},office=${offices[officeId]}">
            <tr>
                <td th:text="${user.fullName}">Fred User</td>
                <td th:text="${user.userId}">fred</td>
                <td th:text="${office.name} (${officeId})">Madison, Wisconsin (madison)</td>
                <th:block th:each="role: ${roles}">
                    <td th:text="${#lists.contains(user.roles, role)} ? 'yes'"></td>
                </th:block>
            </tr>
        </tbody>

我尝试了offices[officeId] 的几种变体,试图从 Map 对象中检索办公室名称。没有th:with 语句的表达式的完整形式看起来像offices[user.officeId].name。我已经转储了办公室地图以确保它不为空,并且它充满了数据。

无论我做什么,我都会得到一些变化:

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "${office} (${officeId})"

只是评论:在使用 Freemarker 几年之后,它已经变得足够成熟,可以为您提供几乎超自然的洞察力错误消息,这非常烦人。

【问题讨论】:

    标签: spring-mvc thymeleaf


    【解决方案1】:

    我认为这里的问题不是th:with。事实上,这句话:&lt;td th:text="${office.name} (${officeId})"&gt;Madison, Wisconsin (madison)&lt;/td&gt; 与错误消息相匹配。我建议将其更改为类似的内容以修复它/使其更具可读性:

    <td>
        <span th:text="${office.name}" /> (<span th:text="${officeId}" />)
    </td>
    

    或保留原来的语法

    <td th:text="${office.name + ' (' + officeId + ')'}">Madison, Wisconsin (madison)</td>
    

    【讨论】:

    • 总结一下:我不应该把括号塞在那里。我想我有暂时的括号盲。
    • 我也刚刚发现“with”在这种情况下是没有用的。它将 office 的值设置为列表中的第一个,并且不会为每一行更新。
    • @k-den th:with 应该以您想要的方式与th:each 一起使用......我刚刚用我自己的测试用例进行了验证。您可以在其他地方覆盖变量吗?
    猜你喜欢
    • 2016-11-05
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多