首页 > 解决方案 > 如何根据 href 链接动态更改 Thymeleaf 片段

问题描述

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

这是显示我的意思的最小生殖示例。


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

链接

<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,我发现当前使用控制器返回片段名称的解决方案对我的情况来说非常清晰和简单。

可能我可以使用Fragment Expressions,但我不确定如何准确。
任何建议表示赞赏。

标签: javaspringtemplatesthymeleaf

解决方案


我会这样表达语法:

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

推荐阅读