springboot温故日志(二),thymeleaf

本文介绍如何在Spring Boot项目中配置并使用Thymeleaf模板引擎,涵盖依赖配置、基础配置、HTML引入方法及常用标签等核心内容。

1、依赖配置

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

2、基础配置

application.properties文件配置中

spring.thymeleaf.cache = true      #启动模板缓存
spring.thymeleaf.encoding = UTF-8      #模板编码
spring.thymeleaf.mode = HTML5      #应用于模板的模板模式
spring.thymeleaf.prefix = classpath:/templates/      #指定模板页面存放路径
spring.thymeleaf.suffix = .html      #指定模板

3、html引入模板引擎

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

上述用于引入thymeleaf模版引擎标签。
使用关键字“th”标注的标签是Thymeleaf模版提供的标签。
例1:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" media="all" 
    		href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
    <title>Title</title>
</head>
<body>
    <p th:text="${hello}">欢迎进入Thymeleaf的学习</p>
</body>
</html>

4、常用标签

th: 标签说明
th:insert布局标签,替换内容到引入的文件,例3
th:replace页面片段包含(类似JSP中的include标签),例2
th:each元素遍历(类似JSP中的c:foreach标签),例2
th:if条件判断,如果为真
th:unless条件判断,如果为假
th:switch条件判断,进行选择性匹配,例2
th:case条件判断,进行选择性匹配,例2
th:value属性值修改,指定标签属性值
th:href用于设定链接地址
th:src用于设定链接地址
th:text用于指定标签显示的文本内容

例2

header.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" 
    th:fragment="header(title,keywords)">
    ......
</html>

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <!-- 载入文章头部页面,位置在/client文件夹下的header模板页面,模板名称th:fragment为header -->
    <div th:replace="/client/header::header(null,null)"/>
    <body>
        <div th:each="item : ${list}">
        	<!-- ${item.enable}可以直接用*{enable} -->
            <div th:switch="${item.enable}">
                <p th:case="1">
                	......
                </p>
                <p th:case="0">
                	......
                </p>
            </div>
        </div>
    </body>
</html>

5、标准表达式

说明表达式语法
变量表达式${…}
选择变量表达式(java对象属性,与上面${}连用),例2*{…}
消息表达式(用于国际化设置)#{…}
链接URL表达式,例1@{…}
片段表达式,例3~{…}

例3

片段表达式~{},用来标记一个片段模版,并根据需要移动或传递给其他模版。其中,最常见的用法是使用th:insert或th:replace属性插入片段。

<div th:insert="~{thymeleafDemo::title}"></div>

6、变量表达式 ${…}中的内置对象

#ctx  上下文对象
#vars  上下文变量
#locale  上下文区域设置
#request (仅限Web Context)HttpServletRequest对象
#response (仅限Web Context)HttpServletResponse对象 
#session (仅限Web Context)HttpSession对象(注:最初使用时记得在controller的相应handle中添加session参数,否则sessen对象没有实例化,为空)
#servletContext (仅限Web Context)ServletContext对象

文章内容输出来源:拉勾教育Java高薪训练营

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jason559

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值