SpringBoot中使用模版引擎Thymeleaf语法
以前前端交给我们的页面时 html 然后我们需要转换成jsp页面来实现页面的组装 ,当我们将框架换成springboot 时,springboot推荐我们使用模版引擎 如:Thymeleaf、freemarker等。
第一步我们要在项目中导入jar包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
模版引擎的作用:就是取得数据并加以处理,最后显示出数据,可以让(网站)程序实现界面与数据分离,业务代码与逻辑代码分离,从而提升开发效率
第二步:当我们导入jar包完成后,在你的配置文件(application.yml)中添加如下配置
spring:
thymeleaf:
# 是否使用缓存
cache: false
# 默认编码格式
encoding: UTF-8
# 使用的模型是什么
mode: HTML5
# 配置文件前缀
prefix: classpath:/templates/
# 配置文件后缀
suffix: .html
第三步:要在配置文件的基础上,在项目的resources文件夹下的templates中添加模版页面,并在配置文件中引入如下代码,来使用Thymelaf
<html xmlns:th="http://www.thymeleaf.org">
th 语法
关键字 | 功能描述 | 案例 |
---|---|---|
th:id | 替换id | <input th:id="'xxx' + ${collect.id}"/> |
th:text | 文本替换/转义 | <p th:text="${collect.description}">description</p> |
th:utext | 支持html的文本替换/不转义 | <p th:utext="${htmlcontent}">conten</p> |
th:object | 替换对象 | <div th:object="${session.user}"> |
th:value | 属性赋值 | <input th:value="${user.name}" /> |
th:with | 变量赋值运算 | <div th:with="isEven=${prodStat.count}%2==0"></div> |
th:style | 设置样式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" |
th:onclick | 点击事件 | th:onclick="'getCollect()'" |
th:each | 属性遍历 | tr th:each="user,userStat:${users}"> |
springboot项目默认查找文件位置:
- /src/java/resources/static
- /src/java/resources/public
- /src/java/resources/templates