Spring boot 2.1 中Thymeleaf layout的使用注意事项

首先,需要检查依赖的包,可参考 https://ultraq.github.io/thymeleaf-layout-dialect/Installation.html 。或直接在pom.xml中添加

		<dependency>
			<groupId>nz.net.ultraq.thymeleaf</groupId>
			<artifactId>thymeleaf-layout-dialect</artifactId>
			<version>2.3.0</version>
		</dependency>

这是对layout dialect的依赖。

在使用时,首先定义模板default.html,放置位置在resources/templates中,我讲模板放在其子目录layout中。模板格式如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no" />
	<title>Insert title here</title>
	
	<link href="/webjars/materializecss/1.0.0-rc.2/css/materialize.css" type="text/css" 
		rel="stylesheet" media="screen,projection" />
</head>
<body>
	<section layout:fragment="content">
		<p>Page content goes here</p>
	</section>
	
	<script src="/webjars/jquery/3.3.1-1/jquery.js"></script>
	<script src="/webjars/materializecss/1.0.0-rc.2/js/materialize.js"></script>
</body>
</html>

这里注意两个地方,一个是<html>标签中的xmlns:layout的设置,另一个是<section>layout:fragment的设置,其值是其他页面引用此模板时指定的fragment值。

使用此模板的页面代码如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	layout:decorate="~{layout/default}">
<head lang="en">
<title>Search</title>
</head>
<body>
	<div class="row" layout:fragment="content">
		<h4 class="indigo-text center">Please enter your name</h4>
		<form action="/result" method="get" class="col1 sl2">
			<div class="row center">
				<div class="input-field col s6 offset-s3">
					<i class="mdi-action-search prefix"></i>
					<input id="search" name="search" type="text" class="validate"/>
					<label for="search">Search</label>
				</div>
			</div>
		</form>
	</div>
</body>
</html>

需要注意的两个地方:

1. html标签中layout:decorate的设置。有两种写法,一种是

layout:decorate="layout/defalut"

另外一种是上面代码中写的

layout:decorate="~{layout/default}"

路径都是相对resources/templates目录的。

2. div标签中的layout:fragment值的设置。其值应设置成模板中section中的layout:fragment的值

猜你喜欢

转载自blog.csdn.net/leon_founder/article/details/82501043