Thymeleaf layout with multiple contents

前端 未结 1 1418
盖世英雄少女心
盖世英雄少女心 2021-01-06 09:57

I\'m new on Thymeleaf template engine, and I\'m making an application with Spring Boot and Spring MVC. I\'m working just with application.properties for the con

相关标签:
1条回答
  • 2021-01-06 10:33

    You could do something like this. Let's say you create a page where all other content will be embedded - main.html. It will look something like this:

    <!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>
    

    Then you want to create some page which will be embedded in your main.html page - 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>
    

    The goal is to replace <div th:include="${page} :: ${fragment}"></div> within main.html with the content from some-page.html. In controller, that will look like this:

    @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')";
        }
    }
    

    And there you go! Every time when you want to swap content in main.html, you just change page and fragment parameters within string in your controller.

    0 讨论(0)
提交回复
热议问题