首页 文章

具有多个内容的Thymeleaf布局

提问于
浏览
4

我用Spring Boot和Spring MVC制作应用程序 . 我正在使用 application.properties 进行配置 .

我想知道我怎么只能写 ONE 布局但是许多文件中的内容:例如 content1.htmlcontent2.html 等,并使用已经有 Headers ,页脚的布局 .

如果可能,我如何从控制器发送将在布局中替换的内容文件?

1 回答

  • 5

    你可以这样做 . 假设您创建了一个页面,其中嵌入了所有其他内容 - main.html . 它看起来像这样:

    <!doctype html>
    <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" xmlns="http://www.w3.org/1999/xhtml">
    
    <div th:fragment="mainPage(page, fragment)">
        <h4>Some header</h4>
        <div th:include="${page} :: ${fragment}"></div>
        <h4>Some footer</h4>
    </div>
    </html>
    

    然后你想创建一些将嵌入你的 main.html 页面的页面 - some-page.html

    <!doctype html>
    <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" xmlns="http://www.w3.org/1999/xhtml">
    <div th:fragment="somePage">
        <h1>${title}</h1>
    </div>
    </html>
    

    目标是将 main.html 中的 <div th:include="${page} :: ${fragment}"></div> 替换为 some-page.html 中的内容 . 在控制器中,它将如下所示:

    @Controller
    public class DemoController {
    
        @RequestMapping
        public String somePage(Model model) {
            // Note that you can easy pass parameters to your "somePage" fragment
            model.addAttribute("title", "Woa this works!");
            return "main :: mainPage(page='some-page', fragment='somePage')";
        }
    }
    

    你去吧!每次要在 main.html 中交换内容时,只需在控制器中的字符串中更改 pagefragment 参数 .

相关问题