Java 如何根据href链接动态更改Thymeleaf片段
我想用Thymeleaf片段构建一个页面,这些片段根据下面的链接动态呈现。Java 如何根据href链接动态更改Thymeleaf片段,java,spring,templates,thymeleaf,Java,Spring,Templates,Thymeleaf,我想用Thymeleaf片段构建一个页面,这些片段根据下面的链接动态呈现。 我在运行时通过Spring控制器解析片段名称时遇到了一个问题 下面是一个简单的例子来说明我的意思 我有list.html页面,有两个链接list 1和list 2,图片和代码如下: 相关的Spring控制器如下所示: @GetMapping(“列表”) 公共字符串getListsPage(模型){ model.addAttribute(“fragmentName”、“listAll”); 返回“列表”; } @G
我在运行时通过Spring控制器解析片段名称时遇到了一个问题 下面是一个简单的例子来说明我的意思
我有
list.html
页面,有两个链接list 1和list 2,图片和代码如下:
相关的Spring控制器如下所示:
@GetMapping(“列表”)
公共字符串getListsPage(模型){
model.addAttribute(“fragmentName”、“listAll”);
返回“列表”;
}
@GetMapping(“列表/列表1”)
公共字符串getAllItems(模型){
model.addAttribute(“list1”,itemService.getList1());
model.addAttribute(“fragmentName”、“list1”);
返回“列表”;
}
@GetMapping(“列表/列表2”)
公共字符串getAllItems(模型){
model.addAttribute(“list2”,itemService.getList2());
model.addAttribute(“fragmentName”、“list2”);
返回“列表”;
}
运行时未解决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
页面代码所示
请不要建议我,我不想使用AJAX,我发现当前使用controller返回片段名称的解决方案对于我的情况非常清楚和简单
可能我可以使用,但我不确定具体使用方法。非常感谢您的建议。我将用以下语法表达:
<th:block th:include="~{${'fragments/lists/' + fragmentName} :: ${fragmentName}}"></th:block>
感谢您的帮助,它就像魔术一样