spring boot_web开发:thymeleaf的引入和相关语法

本文介绍了在spring boot项目中引入thymeleaf模板引擎的原因和方法。内容包括thymeleaf的基本语法,如th:text和th:attr等功能,以及如何配置和使用thymeleaf进行动态页面渲染。开发者可以通过导入命名空间并在html文件中应用thymeleaf语法来实现页面内容的动态更新。详细教程和官方文档链接可供进一步学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模板引擎thymeleaf

当项目以jar包的方式进行打包,并且该boot项目中有嵌入式的tomcat的时候,该项目就不支持类似于jsp的动态页面,如果只用静态的html页面的话,开发会极不方便,这时我们就需要引入一个模板引擎。

spring boot 推荐使用thymeleaf 模板引擎!

thymeleaf在spring boot项目中的引用

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

版本系统会自动配置好,当然也可以自行设置 thymeleaf 的版本,切换thymeleaf版本:

<properties>
		<thymeleaf.verson>3.0.9</thymeleaf.verson>
		<!-- 布局功能的支持程序   thymeleaf3主程序	layout2以上版本 -->
		<!-- thymeleaf2		layout1版本 -->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
	</properties>

thymeleaf的语法格式

在IDEA中按住ctrl+N可以搜索类名,按此方式找到ThymeleafProperties类,在该类中可以看到:

public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";

在thymeleaf包 中已经帮我们自动引入了返回字符串的前缀和后缀渲染。
只要我们把HTML页面放在classpath:/templates/中,thymeleaf就能帮我们自动渲染。
使用

  1. 导入命名空间
    在相应的html页面上端,导入thymeleaf的命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  1. 使用thymeleaf的语法
    th:text;改变当前元素里面的文本内容;
    th:任意html;来替换原生属性的值
    等等,更详细的参照官方文档(中文版)
    链接:https://pan.baidu.com/s/1lGHYR1MW8qrGnCoQmBarQw
    提取码:qth6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值