springspring-mvcrazorthymeleaf

Extend A View With Thymeleaf


is it possible extend a shared view with thymeleaf?

I saw that is possible use framents but is not what I want. Instead I want something similar to .NET MVC, with something like @RenderBody() and another view that extend the shared view by including the shared view.


Solution

  • You can use the Thymeleaf Layout Dialect to extend a view.

    Layout page

    <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
        ...
        <body layout:fragment="body">
          ...
        </body>
    </html>
    

    Content page

    In your content page, you refer to the layout (decorator) page using the layout:decorator attribute.

    <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="layout.html">
        ...
        <body layout:fragment="body">
          <p>Actual page content</p>
        </body>
    </html>
    

    It is possible to have multiple fragments in one page.

    <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
        ...
        <body>
          <div layout:fragment="content"></div>
          <footer layout:fragment="footer"></footer>
        </body>
    </html>