【问题标题】:How to change Thymeleaf fragments dynamically depending on the href link如何根据 href 链接动态更改 Thymeleaf 片段
【发布时间】:2021-04-13 20:06:56
【问题描述】:

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

这是一个最小的繁殖例子来说明我的意思。


我有list.html 页面,其中包含两个链接List 1List 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,但我不确定具体如何。
任何建议表示赞赏。

【问题讨论】:

    标签: java spring templates thymeleaf


    【解决方案1】:

    我会这样表达语法:

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

    【讨论】:

    • 感谢您的帮助,它就像魔术一样工作
    猜你喜欢
    • 2017-01-05
    • 2021-08-15
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2011-01-23
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多