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

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值