Thymeleaf:自定义布局

by kevin 3. 三月 2021 14:01 >

1.简介

页面需要共享常见的页面组件,例如页眉,页脚,菜单等。Thymeleaf使用自定义方言解决了这一问题,如创建布局,自定义标题或head元素合并。

2. Maven依赖

首先,看一下将Thymeleaf与Spring集成所需的必需配置。thymeleaf库需要依赖:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

请注意,对于Spring 4项目, 必须使用thymeleaf-spring4库而不是thymeleaf-spring5

还需要自定义布局方言的依赖项:

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.4.1</version>
</dependency>
springboot项目,添加以下依赖就可以启动。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

3.命名空间和属性处理器的功能

配置完成后,就可以开始使用布局名称空间和五个新的属性处理器:decoratetitle-patterninsertreplacefragment。

为了创建要用于HTML文件的布局模板,创建了以下文件,命名为template.html

<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
...
</html>

将名称空间从标准xmlns:th =“ http://www.thymeleaf.org”更改为xmlns:layout =“ http://www.ultraq.net.nz/thymeleaf/layout

在HTML文件中使用属性处理器。

3.1。布局:片段

为了在布局或可重复使用的模板中创建可被共享相同名称的部分替换的自定义部分,在template.html正文中使用fragment属性:

<body>
    <header>
        <h1>New dialect example</h1>
    </header>
    <section layout:fragment="custom-content">
        <p>Your page content goes here</p>
    </section>
    <footer>
        <p>My custom footer</p>
        <p layout:fragment="custom-footer">Your custom footer here</p>
    </footer>
</body>

请注意,有两个部分将被自定义HTML取代-内容和页脚。

如果找不到任何片段,编写将要使用的默认HTML也很重要。

3.2。布局:装饰

需要做的下一步是创建一个HTML文件,该文件将通过布局进行装饰:

<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
  layout:decorate="~{template.html}">
<head>
<title>Layout Dialect Example</title>
</head>
<body>
    <section layout:fragment="custom-content">
        <p>This is a custom content that you can provide</p>
    </section>
    <footer>
        <p layout:fragment="custom-footer">This is some footer content
          that you can change</p>
    </footer>
</body>
</html>

如第三行所示,使用layout:decorate并指定装饰器源。布局文件中与内容文件中的片段匹配的所有片段将被其自定义实现替换。

3.3。布局:标题模式

鉴于布局方言会自动使用内容模板中的布局标题覆盖布局标题,可以保留在布局中找到的部分标题。

例如,可以创建面包屑或在页面标题中保留网站名称。在这种情况下,layout:title-pattern处理器会提供帮助。需要在布局文件中指定的所有内容是:

<title layout:title-pattern="$LAYOUT_TITLE - $CONTENT_TITLE">Baeldung</title>

因此,上一段中呈现的布局和内容文件的最终结果将如下所示:

<title>Baeldung - Layout Dialect Example</title>
3.4。布局:插入/布局:替换

第一个处理器layout:insert类似于Thymeleaf的原始th:insert,但是允许将整个HTML片段传递给插入的模板。如果有一些要重用的HTML,但其内容过于复杂而无法单独使用上下文变量来确定或构造,则此功能非常有用。

第二个布局layout:replace,与第一个类似,但是具有th:replace的行为,该行为实际上将使用定义的片段代码替换host标签。

分享到: 更多

打赏请我喝果汁咯

支付宝 微信

关于我

80后,单身,平庸的程序员。

喜欢看书,乐于交友,向往旅游。

遇建Kevin

FluentData交流群:477926269

Fluentdata