-6ren"> -我正在使用 sping mvc 4.2.2 和 thymeleaf-spring4 2.1.2 构建一个 Web 应用程序,并且大多数页面共享相同的标题、侧边栏等。因此,我决定只有一个 view (.-6ren">
gpt4 book ai didi

java - 作为变量传递时,Thymeleaf 片段无法解析,即

转载 作者:行者123 更新时间:2023-12-02 04:04:56 24 4
gpt4 key购买 nike

我正在使用 sping mvc 4.2.2 和 thymeleaf-spring4 2.1.2 构建一个 Web 应用程序,并且大多数页面共享相同的标题、侧边栏等。因此,我决定只有一个 view (.html) 替换子 div 取决于 url 中的参数 page

页面名称将被 Controller 转换为片段名称:

//SpringTestHello.java
@Controller
public class SpringTestHello {
@RequestMapping("/test")
public String testMap(@RequestParam(value="page", required=false, defaultValue="overview") String page, Model model) {
if (page.equalsIgnoreCase("overview"))
page = "overview :: overview";
if (page.equalsIgnoreCase("user"))
page = "overview :: user";
model.addAttribute("page", page);
return "main_page";
}
}

主页面将用 page 属性替换子 div:

<!--main_page.html-->
<div id="pageContent" th:if="${!page.isEmpty()}"
th:replace="${page}">Main Content here</div>
<!--This causes exception-->

但是这会导致 TemplateInputException:

org.thymeleaf.exceptions.TemplateInputException: 
Error resolving template "overview :: overview", template might not exist or might not be
accessible by any of the configured Template Resolvers (main_page:123)

使用字符串文字时可以按预期工作:

<!--main_page.html-->
<div id="pageContent" th:replace="overview :: overview"></div>
<!--This shows the correct fragment-->

为什么片段名称作为参数传递时无法解析模板?

最佳答案

您应该在替换语句中预处理 ( See Docs ) ${page} ,以便它在任何其他处理之前发生,从而允许正确包含片段。

您的替换将变为(请注意 ${page} 周围的双下划线):

<div id="pageContent" th:if="${!page.isEmpty()}"
th:replace="__${page}__">Main Content here</div>

我还建议您查看 Thymeleaf Layout Dialect这非常适合您当前的用例——用一些标准内容装饰不同的页面。

关于java - 作为变量传递时,Thymeleaf 片段无法解析,即 <div th :replace ="${page}">,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34430090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com