Extend A View With Thymeleaf

2019-04-12 01:36发布

问题:

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.

回答1:

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>