使用 Thymeleaf 扩展视野

问题描述 投票:0回答:2

是否可以扩展与 thymeleaf 的共享视图?

我看到可以使用framents,但这不是我想要的。 相反,我想要类似于 .NET MVC 的东西,比如 @RenderBody() 和另一个通过包含共享视图来扩展共享视图的视图。

spring spring-mvc razor thymeleaf
2个回答
10
投票

您可以使用 Thymeleaf 布局方言 来扩展视图。

布局页面

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

内容页面

在内容页面中,您使用

layout:decorator
属性引用布局(装饰器)页面。

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

一页中可以有多个片段。

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

0
投票

看起来 Thymeleaf 3.1 版模板扩展应该使用教程:使用 Thymeleaf (3.1.2.RELEASE),第 8.5 章布局继承中描述的其他机制来完成:

布局是(

src/main/resources/templates/layout/layout_simple.html
):

<!DOCTYPE html>
<html lang="en" th:fragment="layout(title, main)"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:replace="${title}">Layout title</title>
</head>
<body>
<header>Common block: header</header>
<main id="mainpart" th:replace="${main}">
    <p><em>This content must not be visible.</em></p>
</main>
<footer>Common block: footer</footer>
</body>
</html>

页面是(

src/main/resources/templates/thymeleaf_first_page_simple.html
):

<!DOCTYPE html>
<html th:replace="~{layout/layout_simple :: layout(~{::title}, ~{::main})}"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf demo simple</title>
</head>
<body>
<main>
    <h1>Thymeleaf template extension simple demo</h1>
    <p>Actual page content: [<th:block th:text="${modelValue}" />]</p>
</main>
</body>
</html>

结果是:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf demo simple</title>
</head>
<body>
<header>Common block: header</header>
<main>
    <h1>Thymeleaf template extension simple demo</h1>
    <p>Actual page content: [some simple value from the model]</p>
</main>
<footer>Common block: footer</footer>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.