【问题标题】:Thymeleaf fragment cannot be resolved when passing as variable i.e. <div th:replace="${page}">作为变量传递时无法解析 Thymeleaf 片段,即 <div th:replace="${page}">
【发布时间】:2016-03-29 13:24:27
【问题描述】:

我正在使用 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-->

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

【问题讨论】:

    标签: java spring web-services spring-mvc thymeleaf


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 效果很好!谢谢!我也打算在阅读后切换到布局方言
    猜你喜欢
    • 2020-12-31
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 2016-09-21
    • 2020-06-02
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多