基于springboot框架的thymeleaf入门

一、什么是Thymeleaf?

此处可参考博文

Thymeleaf是一个模板引擎,可以完全替代jsp,类似的模板引擎还有Velocity/FreeMarker。
ThymeLeaf的主要特点:
  • 有网络和无网络环境下均可运行
    前端可以查看页面的静态效果,浏览器解析html时会忽略未定义的标签属性;
    后台可以查看带数据的动态页面,当有数据返回到页面时,Thymeleaf标签会动态地替换掉静态内容。

  • 开箱即用
    它提供标准和spring标准两种语言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的语言。

  • **提供spring标准语言和一个与springmvc完美集成的可选模块,快速实现表单绑定、属性编辑器、国际化等功能

二、thymeleaf需要配置什么?

1. 引入所依赖的jar

在springboot配置文件pom.xml中添加thymeleaf所依赖:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. 配置thymeleaf视图解析器

在springboot中找到application.properties文件,在此文件中添加thymeleaf视图解析器:

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end

3. 常用语法

  1. 创建html
    需要在.html文件中添加,只有添加了词条语句,下文中才能正确使用th等标签:
	<html xmlns:th="http://www.thymeleaf.org">
	```

2. 获取变量值“${}”
```html
       <!--p中原有的值“333”只是为了给前端开发时做展示用的。
       thymeleaf有一个特性:在无网络的情况下也可以运行,只是运行出来的界面展示的是模拟数据,由此便很好做到了前后端分类,便于开发。-->
   <p th:text="'Hello!, ' + ${name} + '!'">3333</p>
  1. 选择变量表达式“*{}”
 <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Tom</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Ford</span>.</p> 
</div> 
下面这种方式与上一中等价:
<div>
    <p>Name: <span th:text="${session.user.firstName}">Tom</span>.</p> 
    <p>Surname: <span th:text="${session.user.lastName}">Ford</span>.</p> 
</div>
  1. 链接表达式
<a th:href="@{/logout}" class="signOut"></a>
  1. 文本替换
<span th:text="'Welcome to my world, ' + ${user.name} + '!'">

想要更详细了解thymeleaf各种标签,可查阅此博文link.

猜你喜欢

转载自blog.csdn.net/HW_870754395/article/details/84628953
今日推荐