SpringBoot--模板引擎(Thymeleaf)

1、SpringBoot对静态资源的映射规则;

 (1) webjars:以jar包的方式引入静态资源,目录在 classpath:/META-INF/resources/webjars/ **下

在这里插入图片描述

<!--引入jquery-webjar-->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.3.1</version>
		</dependency>

 (2) “/**” 访问当前项目的任何资源,都去(静态资源的文件夹)找映射

	1. "classpath:/META-INF/resources/"
	2. "classpath:/resources/"
	3. "classpath:/static/"
	4. "classpath:/public/"
	5. "/":当前项目的根路径

 (3) 静态资源文件夹下的所有index.html页面,被"/**"映射

3、模板引擎(Thymeleaf)

 3.1 引入thymeleaf

	
	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
          	2.1.6
	</dependency>
   <!--切换thymeleaf版本(可选)-->
	<properties>
			<thymeleaf.version>3.0.10.RELEASE</thymeleaf.version>
			<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
	</properties>

 3.2 Thymeleaf使用

  ​ Thymeleaf能自动渲染classpath:/templates/路径下的html页面

  (1) 导入thymeleaf的名称空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

   (2) 使用thymeleaf语法

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>

 3.3 语法规则

  (1) th:任意html属性来替换原生属性的值

  (2) 常用操作表达式

${...}:获取变量值;

*{...}:选择表达式,和${}在功能上是一样;
  
#{...}:获取国际化内容

@{...}:定义URL;
    		
~{...}:片段引用表达式

 3.4 模板引擎修改后实时生效

  (1) 禁用模板引擎的缓存

# 禁用缓存
spring.thymeleaf.cache=false 

  (2) 页面修改完成以后ctrl+f9,重新编译

 3.5 thymeleaf公共页面元素抽取

1、抽取公共片段
<div th:fragment="copy">
	公共片段
</div>

2、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名

 三种引入公共片段的th属性:

  th:insert:将公共片段整个插入到声明引入的元素中

  th:replace:将声明引入的元素替换为公共片段

  th:include:将被引入的片段的内容包含进这个标签中

<footer th:fragment="copy">
	公共片段
</footer>

引入方式
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>

<div>
    <footer>
        效果一
    </footer>
</div>

<footer>
	效果二
</footer>

<div>
	效果三
</div>
发布了121 篇原创文章 · 获赞 45 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41596568/article/details/102822894