spring 使用Thymeleaf扩展视图

72qzrwbm  于 4个月前  发布在  Spring
关注(0)|答案(2)|浏览(54)

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

mhd8tkvw

mhd8tkvw1#

您可以使用Thymeleaf Layout Dialect扩展视图。

布局页面

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

kcrjzv8t

kcrjzv8t2#

看起来像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>

相关问题