Thymeleaf Multiple Content Schema

I am new to Thymeleaf template template and I am building an application with Spring Boot and Spring MVC. I just work with application.propertiesfor configuration.

I want to know how I can write only ONE layout, but contents in many files: for example content1.html, content2.htmletc. and use a layout that already has a header, footer.

If possible, how can I send a content file from the controller that will be replaced in the layout?

+4
source share
1 answer

You could do something like this. Say you create a page where all other content is added 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 a page that will be embedded in your page 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>

The goal is to replace <div th:include="${page} :: ${fragment}"></div>in main.htmlwith content some-page.html. In the controller, it 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 here you are! Every time you want to change the content in main.html, you just change the parameters pageand fragmentin the line in the controller.

+4
source

Source: https://habr.com/ru/post/1659095/


All Articles