【发布时间】:2021-04-13 20:06:56
【问题描述】:
我想用 Thymeleaf 片段构建一个页面,这些片段会根据以下链接动态呈现。
我在通过 Spring 控制器在运行时解析片段名称时遇到问题。
这是一个最小的繁殖例子来说明我的意思。
我有list.html 页面,其中包含两个链接List 1 和List 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