SpringBoot项目开发系列:Thymeleaf 模版引擎

1.thymeleaf介绍

    Thymeleaf 官网:www.thymeleaf.org,可下载操作手册
    Thymeleaf 可以在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看静态效果,也可以让程序员在服务器查看带   数据的动态页面效果
    html模板引擎,它可以完全替代 JSP,提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能

2.在application.properties中,进行如下配置

springboot封装的thymeleaf默认是2.x版本,如果想使用最新的3.x版本可以在< properties >中配置版本

3.

下面详细分享一些常用用法:

      请提前在项目resources目录下创建css、js文件夹,分别创建index.css,common.js文件,并在js文件夹下放入jquery.min.js,后面的html和模版需要用到

编号 属性 描述 示例
1 th:text 计算其值表达式并将结果设置为标签的标签体 <p th:text="${userName}">中国</p>,值为 null 为空时,整个标签不显示任何内容。
2 th:utext th:text 会对结果中的特殊字符转义,th:utext 不会转义,适合后端直接向前端输出 html 标签的内容 <p th:utext="${userInfo}">中国</p>,,userInfo可以是html内容。
3 th:attr 为标签中的任意属性设置,可以一次设置多个属性 <a href="" th:attr="title='前往百度',href='http://baidu.com'">前往百度</a>
4 th:* 为 html 指定的属性设值,一次设置一个 <a href="" th:title='前往百度' th:href="'http://baidu.com'">前往百度</a>
5 th:alt-title 同时为 alt 与 title 属性赋值 <a href="#" th:alt-title="'th:A-B'">th:A-B</a>
6 th:lang-xmllang 同时为 lang 、xmllang 属性赋值 <head lang="en" th:lang-xmllang="en">
7 th:fragment 定义模板片段 <div th:fragment="copy">
8  th:insert 将被引用的模板片段插⼊到自己的标签体中 <div th:insert="~{footer :: copy}"></div>
9 th:replace 将被引用的模板片段替换掉自己 <div th:replace="footer :: copy"></div>
10 th:include 类似于 th:insert,⽽不是插⼊⽚段,它只插⼊此⽚段的内容
<div th:include="footer :: copy"></div>
11 th:remove 删除模板中的某些代码片段 <tr th:remove="all">...
12 th:each 迭代数据,如 数组、List、Map 等 <tr th:each="user : ${userList}">...
13 th:if 条件为 true 时,显示模板⽚段,否则不显示
<p th:if="${isMarry}">已婚1</p>
14

th:unless

条件为 false 时,显示模板⽚段,否则不显示
<p th:unless="!${isMarry}">已婚2</p>
15

th:switch 

与 Java 中的 switch 语句等效,有条件地显示匹配的内容 <div th:switch="1">
16 th:case 配合 th:switch 使用 <div th:switch="1">
    <p th:case="0">管理员</p>
    <p th:case="1">操作员</p>
    <p th:case="*">未知用户</p>
</div>
17  th:with 定义局部变量 <div th:with="userFirst=${userList[0]}">
18

th:inline

禁用内联表达式,内联js,内联css <script type="text/javascript" th:inline="javascript">
       
       

(1)使用模版:定义公用头部css和尾部js引用,在其他页面中引用模版,更换样式时,只需更换模版中的引用即可
    操作步骤:在resources—templates目录下创建一个template的文件夹,里面创建common.html文件,文件内容如下,以下有两种用法:

在需要引用头部、尾部的html文件中,使用 th:replace=“template/common :: header” 模版路径 :: 模版名称

(2)变量表达式: Spring EL表达式(在Spring术语中也叫model attributes)。如下所示

       直接 . 出后台返回对象属性       <span th:text="${user.name}">  
       直接循环出后台返回数组-list属性  <ul><li th:each="user: ${users}" th:text="${user.name}"></li></ul>
       可以写th:if 判断,             <div th:if="${user.age} > 20">我大于20啦</div>
       th:unless与 if 相反            <div th:unless="${user.age} > 20">我还年轻</div>

5.贴下我的代码和运行效果,项目中常用的就这些

效果如下:

猜你喜欢

转载自blog.csdn.net/qq_34709784/article/details/105118261