java - 如何根据 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,但我不确定如何准确。
任何建议表示赞赏。
解决方案
我会这样表达语法:
<th:block th:include="~{${'fragments/lists/' + fragmentName} :: ${fragmentName}}"></th:block>
推荐阅读
- vue.js - 如何修复“多个根元素”v-for 错误
- python - 使用 selenium python 浏览页面
- java - 从文件中删除所有 java 关键字
- c++ - 这个表达式是如何工作的?(c^0,c^32);
- ssh - 通过 SSH 在 32 位 CentOS 7 服务器上安装 Rust
- reactjs - 如何通过反应实时创建实时搜索填充
- c++ - 如何将我的代码从 O(n^2) 优化到 nlog(n)
- python - ImportError:无法从“sqlalchemy.sql.expression”导入名称“_literal_as_text”
- javascript - 构造函数破坏逻辑
- json - Ionic React 太慢,无法在 IonCard 组件中呈现包含 100 多个对象的 JSON 文件