Spring Boot 模板引擎 Thymeleaf

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。类似 JSP,Velocity,FreeMaker 等,它也可以轻易的与 Spring 等框架进行集成作为 Web 应用的模板引擎。虽然我们现在比较流行 Restfull 的风格,API可以解决很多问题,但有时候可能会用到模板页面。我之前在 Spring MVC 上用 JSP 比较多,由于 Spring Boot 官方默认使用 Thymeleaf,所以我们不妨来试一试。在上一个 spring-boot-jpa 项目已经使用到了,但没详细说明,所以非常有必要学习一下 Thymeleaf 。

引入依赖

pom.xml 加入 Thymeleaf 依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置视图解析器

默认静态文件路径为 classpath:/static/
默认页面映射路径为 classpath:/templates/*.html

在 application.properties 中可以配置 Thymeleaf 模板解析器属性,需要注意的是:在开发过程中需要将 Thymeleaf 缓存关闭。

1
2
3
4
5
6
7
8
# Thymeleaf
#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=HTML5
#spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type=text/html
# 开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false

基础语法

修改 html 标签

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

获取变量值

<p th:text="'您好,'+ ${user.username} "></p>

获取变量值用$符号,对于 javaBean 的话使用变量名.属性名方式获取。$ 表达式只能写在th标签内部,不然不会生效,上面例子就是使用 th:text 标签的值替换p标签里面的值。

未完!

坚持原创技术分享,您的支持将鼓励我继续创作!