模板引擎Thymeleaf基本介绍和使用

2022年7月22日13:13:47

一、序言

虽然目前大部分互联网项目都是基于先后端分离的思想开发,但也存在一些视图和后台代码还是在同个工程的。本文详细讲解SpringBoot视图框架Thymeleaf,一种基于Java语言实现的模板引擎技术。

二、常见标签

<!DOCTYPE html><htmllang="en"xmlns:th="http://www.thymeleaf.org"><head><metacharset="UTF-8"><linkrel="stylesheet"type="text/css"media="all"href="../../css/gtvg.css"th:href="@{/css/gtvg.css}"/><title>Title</title></head><body><pth:text="${hello}">Hello World!</p></body></html>

以上便是常见的Thymeleaf模板代码,xmlns:th="http://www.thymeleaf.org"表示引入模板引擎标签,th:href用于引入外联样式文件,th:text用于动态展示标签的文本内容。Thymeleaf提供了很多标签用于解析视图,大体如下:

标签 注释
th:insert 布局标签,引入具体的内容
th:each 遍历元素
th:replace 引入文件,类似include
th:if 条件判断,如果为真
th:unless 条件判断,如果为假
th:switch 条件判断,跟th:case配合使用
th:value 指定属性标签
th:href 设置超链接
th:src 引入外部资源文件
th:text 指定标签显示的内容

三、标准表达式

3.1 变量表达式${…}

主要用于显示上下文中的变量值,如果上下文中不存在指定内容,则显示默认的内容。

<pth:text="${content}">默认内容</p>

Thymeleaf内置的对象:

ctx、vars、locale:都是作用于上下文对象
request:作用于HttpServletRequest对象
response:作用于HttpServletResponse对象
session:作用于HttpSession对象
servletContext:作用于ServletContext对象

3.2 选择变量表达式*{…}

一般用于从被选定对象中获取属性,比如,从book对象中获取title属性可以这样子写:

<divth:object="${book}"><p>titile:<spanth:text="*{title}">标题</span></p></div>

3.3 消息表达式#{…}

用于国际化内容的动态展示和替换,但需要提供相应的国际化配置信息。SpringBoot默认识别的语言配置为resource下的message.properties,其他国际化语言遵从“文件前缀_语言代码_国家代码.properties”的形式实现,例如:

## login_en_US.properties
login.tip=Please sign in
login.username=Username
login.password=Password
login.rememberme=Remember me
login.button=Login

编写配置文件:

# 国际化文件配置,包名+属性名
spring.messages.basename=com.keduw.login

3.4 链接表达式@{…}

一般用于链接跳转,需要同时传递参数时,需要按照@{链接(参数名=参数值,参数名=参数值…)}的形式,参数值同时支持表达式传值。

<ath:href="@{/order/details(orderId=${o.id})}">view</a>

3.5 片段表达式~{…}

用来标记一个片段传递给其他模板使用,最常用的方式是使用th:insertth:replace属性插入片段,比如:

<divth:insert="~{commonDiv::header}"></div>

将commonDiv模板中的header代码片段添加到指定位置中,Thymeleaf会自动查找“/resources/templates”中的commonDiv模板,header为片段名称。

四、基本使用

Thymeleaf的引入很简单,只需要导入相关依赖,添加指定配置信息即可。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
spring.thymeleaf.cache = true // 启动模板缓存
spring.thymeleaf.encoding = UTF-8 //模板编码
spring.thymeleaf.mode = HTML5
spring.thymeleaf.prefix = classpath:/templates/ //模板页面存放路径
spring.thymeleaf.suffix = .html //模板后缀
  • 作者:林风自在
  • 原文链接:https://blog.csdn.net/hsf15768615284/article/details/108904107
    更新时间:2022年7月22日13:13:47 ,共 2104 字。