有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何根据href链接动态更改Thymeleaf片段

我想用Thymeleaf片段构建一个页面,这些片段根据下面的链接动态呈现
我在运行时通过Spring控制器解析片段名称时遇到了一个问题

下面是一个简单的例子来说明我的意思


我有list.html页面,有两个链接列表1列表2,图片和代码如下:

Links

<body>
  <button type="button"><a th:href="${'/lists/list1'}">List 1</a></button>
  <button type="button"><a th:href="${'/lists/list2'}">List 2</a></button>

  <!-- This doesn't work, the include is not resolved correctly -->
  <th:block th:include="'fragments/lists/' + ${fragmentName}
                        + ' :: ' + ${fragmentName}"></th:block>

  <!-- However static include works well -->
  <th:block th:include="fragments/lists/list1 :: list1"></th:block>
</body>

相关的Spring控制器如下所示:

@GetMapping("lists")
public String getListsPage(Model model) {
    model.addAttribute("fragmentName", "listAll");
    return "lists";
}

@GetMapping("lists/list1")
public String getAllItems(Model model) {
    model.addAttribute("list1", itemService.getList1());
    model.addAttribute("fragmentName", "list1");
    return "lists";
}

@GetMapping("lists/list2")
public String getAllItems(Model model) {
    model.addAttribute("list2", itemService.getList2());
    model.addAttribute("fragmentName", "list2");
    return "lists";
}

运行时未解决fragmentName问题,并引发TemplateInputException异常:

Caused by: org.thymeleaf.exceptions.TemplateInputException: Error resolving
  template ['fragments/lists/' + ${fragmentName} + '], template might not exist
  or might not be accessible by any of the configured Template Resolvers
  (template: "lists" - line 38, col 11)

同时,静态块正常工作,如list.html页代码所示

请不要建议我Spring MVC 3.2 Thymeleaf Ajax Fragments,我不想使用AJAX,我发现当前使用controller返回片段名称的解决方案对于我的情况非常清楚和简单

也许我可以使用Fragment Expressions,但我不确定具体如何使用
如有任何建议,我们将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    我会这样表达语法:

    <th:block th:include="~{${'fragments/lists/' + fragmentName} :: ${fragmentName}}"></th:block>