具有多个内容的Thymeleaf布局

mar*_*rbi 4 layout thymeleaf spring-boot

我是Thymeleaf模板引擎的新手,我正在使用Spring Boot和Spring MVC创建一个应用程序.我正在application.properties为配置工作.

我想知道我怎么能只写ONE布局,但内容在许多文件:例如content1.html,content2.html等,使用已有的页眉,页脚的布局.

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

Bra*_*zic 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>
Run Code Online (Sandbox Code Playgroud)

然后,您想要创建一些将嵌入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>
Run Code Online (Sandbox Code Playgroud)

我们的目标是取代<div th:include="${page} :: ${fragment}"></div>main.html从内容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')";
    }
}
Run Code Online (Sandbox Code Playgroud)

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