Thymeleaf 是一款用于渲染 XML/XHTML/HTML 5 内容的模板引擎。类似 JSP、Velocity、FreeMaker 等,它也可以轻易的与 Spring MVC 等 Web 框架进行集成作为 Web 应用的模板引擎。与其他模板引擎相比,Thymeleaf 最大的特点是能够直接在浏览 器中打开并正确显示模板页面,而不需要启动整个 Web 应用。

pom配置

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

在 application.properties 中添加配置:

spring.thymeleaf.cache=false

前端html页面标签中引入如下:

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

常用语法:

1.赋值、字符串拼接:

<p th:text="${userName}">neo</p>
<span th:text="'Welcome to our application, ' + ${userName} + '!'"></span>

字符串拼接还有另外⼀种简洁的写法:

<span th:text="|Welcome to our application, ${userName}!|"></span>

2.条件判断 If/Unless

Thymeleaf 中使用 th:if 和 th:unless 属性进行条件判断,下面的例子中,   <a> 标签只有在 th:if 中条件成立时才显示:

<a th:if="${flag == 'yes'}"  th:href="@{/home}"> home </a>
<a th:unless="${flag != 'no'}" th:href="@{http://www.baidu.com/}" >baidu</a>

th:unless 与 th:if 恰好相反,只有表达式中的条件不成时,才会显示其内容。
也可以使用(if) ? (then) : (else) 这种语法来判断显示的内容。

3.for 循环

<table>
   <tr th:each="user,iterStat : ${users}"> <td th:text="${user.name}">neo</td>
      <td th:text="${user.age}">6</td>
      <td th:text="${user.pass}">213</td>
      <td th:text="${iterStat.index}">index</td>    </tr>
</table>

iterStat 称作状态变量,属性有:
index:当前迭代对象的 index(从 0 开始计算)
count:当前迭代对象的 index(从 1 开始计算)
size:被迭代对象的⼤⼩
current:当前迭代变量
even/odd:布尔值,当前循环是否是偶数/奇数(从 0 开始计算)

first:布尔值,当前循环是否是第一个

last:布尔值,当前循环是否是最后一个

4.URL

URL 在 Web 应用模板中占据着十分重要的地位,需要特别注意的是 Thymeleaf 对于 URL 的处理是通过语法 @{...} 来处理的。

如果需要 Thymeleaf 对 URL 进行渲染,那么务必使用 th:href、th:src 等属性,下面举一个例子:

<a th:href="@{http://www.ityouknow.com/{type}(type=${type})}">link1</a>
<a href="details.html" th:href="@{http://www.ityouknow.com/{pageId}/can-use-springcloud.html(page Id=${pageId})}">view</a>
<a th:href="@{/list}" class="btn btn-info">Back</a>

设置背景:map.addAttribute("img", "http://www.ityouknow.com/assets/images/neo.jpg");

<div th:style="'background:url(' + @{${img}} + ');'">

5.内联 [ [ ] ]

内联文本:[[...]] 内联文本的表示方式,使用时,必须先用在 th:inline="text/javascript/none" 激活,th:inline 可以在父级标签内使用,甚至作为 body 的标签。内联文本尽管比⽐ th:text 的代码少,不利于原型显示。

文本内联:

<div th:inline="text" > <h1>内联js</h1> <p>Hello, [[${userName}]]</p> <br/>
</div>

脚本内联,脚本内联可以在 js 中取到后台传过来的参数:

<script th:inline="javascript"> var name = [[${userName}]] + ', Sebastian'; alert(name);
</script>

6.内嵌变量

为了模板更加易用,Thymeleaf 还提供了一系列 Utility 对象(内置于 Context 中),可以通过 # 直接访问:

dates:java.util.Date 的功能方法类
calendars: 类似 #dates,面向 java.util.Calendar
numbers:格式化数字的功能方法类
strings:字符串对象的功能类,contains、startWiths、prepending/appending 等
objects:对 objects 的功能类操作
bools: 对布尔值求值的功能方法
arrays:对数组的功能类方法
lists:对 lists 的功能类方法
sets
maps
...

下面用一段代码来举例一些常用的方法:

dates
<p th:text="${#dates.format(date, 'dd/MMM/yyyy HH:mm')}">neo</p> <p th:text="${#dates.createToday()}">neo</p>
<p th:text="${#dates.createNow()}">neo</p>

strings
<p th:text="${#strings.isEmpty(userName)}">userName</p>
<p th:text="${#strings.listIsEmpty(users)}">userName</p>
<p th:text="${#strings.length(userName)}">userName</p>
<p th:text="${#strings.concat(userName)}"></p>
<p th:text="${#strings.randomAlphanumeric(count)}">userName</p>

html5的操作支持:

th:abbr          th:accept             th:accept-charset
th:accesskey             th:action             th:align
th:alt             th:archive             th:audio
th:autocomplete             th:axis             th:background
th:bgcolor             th:border             th:cellpadding
th:cellspacing             th:challenge             th:charset
th:cite             th:class             th:classid
th:codebase             th:codetype             th:cols
th:colspan             th:compact             th:content
th:contenteditable             th:contextmenu             th:data
th:datetime             th:dir             th:draggable
th:dropzone             th:enctype             th:for
th:form             th:formaction             th:formenctype
th:formmethod             th:formtarget             th:fragment
th:frame             th:frameborder             th:headers
th:height             th:high             th:href
th:hreflang             th:hspace             th:http-equivth:icon             th:id             th:inline
th:keytype             th:kind             th:label
th:lang             th:list             th:longdesc
th:low             th:manifest             th:marginheight
th:marginwidth             th:max             th:maxlength
th:media             th:method             th:min
th:name            th:onabort            th:onafterprint
th:onbeforeprint            th:onbeforeunload            th:onblur
th:oncanplay            th:oncanplaythrough            th:onchange
th:onclick            th:oncontextmenu            th:ondblclick
th:ondrag            th:ondragend            th:ondragenter
th:ondragleave            th:ondragover            th:ondragstart
th:ondrop            th:ondurationchange            th:onemptied
th:onended            th:onerror            th:onfocus
th:onformchange            th:onforminput            th:onhashchange
th:oninput            th:oninvalid            th:onkeydown
th:onkeypress            th:onkeyup            th:onload
th:onloadeddata            th:onloadedmetadata            th:onloadstart
th:onmessage            th:onmousedown            th:onmousemove
th:onmouseout            th:onmouseover            th:onmouseup
th:onmousewheel            th:onoffline            th:ononline
th:onpause            th:onplay            th:onplaying
th:onpopstate            th:onprogress            th:onratechange
th:onreadystatechange            th:onredo            th:onreset
th:onresize            th:onscroll            th:onseeked
th:onseeking            th:onselect            th:onshow
th:onstalled            th:onstorage            th:onsubmit
th:onsuspend            th:ontimeupdate            th:onundo
th:onunload            th:onvolumechange            th:onwaiting
th:optimum            th:pattern            th:placeholder
th:poster            th:preload            th:radiogroup
th:rel            th:rev            th:rows
th:rowspan            th:rules            th:sandbox
th:scheme            th:scope            th:scrolling
th:size            th:sizes            th:span
th:spellcheck            th:src            th:srclang
th:standby            th:start            th:step
th:style            th:summary            th:tabindex
th:target            th:title            th:type
th:usemap            th:value            th:valuetype
th:vspace            th:width            th:wrapth:vspace            th:width            th:wrap
th:xmlbase            th:xmllang            th:xmlspace

7.所有可用值表达式: *{…}

比如*{name} 从可用值中查找name,如果有上下文,比如上层是object,则查object中的name属性。

8.操作模板

布局是最常用的功能之一,不论是前端还是后台都避免不了,使用Thymeleaf 布局非常简单,下面来演示一下: 首先定义一个代码片段 copyright.html,放到 layout 目录下:

<footer th:fragment="copyright">
&copy; 2017
</footer>

创建 index.html 在⻚⾯任何地⽅引⼊:

<body> <div th:include="layout/copyright :: copyright"></div>
</body>

layout 是文件夹地址,fileName 是文件名,语法这样写:layout/fileName:htmlhead 。
htmlhead 是指定义的代码⽚段 如 th:fragment="htmlhead"。

转载于:https://www.cnblogs.com/person008/p/9578843.html

Spring boot(五)模板引擎 Thymeleaf相关推荐

  1. 软件架构-Spring boot集成模板引擎swagger2实现

    上次说过springboot其实就是一个CI工具,如何体验出来CI的作用就是持续集成,它可以集成各种的工具,这里说说关于模板的集成引擎和Swagger. (一)Spring boot 集成模板引擎实现 ...

  2. Spring Boot + Drools+模板引擎,优惠券的动态添加以及购物车结算

    目录 二.项目文件结构以及数据库表结构 三.主要项目文件说明 1.pom文件 2.配置文件 3.实体类 4.添加优惠券业务实现 5.购物车结算业务实现 四.实现效果 1.添加优惠券 2.购物车结算 五 ...

  3. Spring Boot整合模板引擎jsp

    为什么80%的码农都做不了架构师?>>>    jsp也算是一种模板引擎吧.整合jsp前,先说一下运行SpringBoot项目的几种方式 1. 运行SpringBoot项目的几种方式 ...

  4. Spring Boot 使用模板引擎

    Spring Boot 推荐使用Thymeleaf.FreeMarker.Velocity.Groovy.Mustache等模板引擎.不建议使用JSP. Spring Boot 对以上几种引擎提供了良 ...

  5. Spring Boot默认模板方案Thymeleaf

    Thymeleaf入门 web开发离不开动态页面的开发,目前来说最主流的方案是Thymeleaf Thymeleaf是一个模板框架,它可以支持多种格式的内容动态渲染非常强大,而且天然是与HTML相融合 ...

  6. Spring Boot 9-FreeMarker模板引擎

    springboot使用freemarker模板引擎 首先引入freemarker <!-- freemarker依赖包 --> <dependency><groupId ...

  7. Spring Boot (四)模板引擎Thymeleaf集成

    一.Thymeleaf介绍 Thymeleaf是一种Java XML / XHTML / HTML5模板引擎,可以在Web和非Web环境中使用.它更适合在基于MVC的Web应用程序的视图层提供XHTM ...

  8. Spring Boot 最佳实践(四)模板引擎Thymeleaf集成

    ## 一.Thymeleaf介绍 Thymeleaf是一种Java XML / XHTML / HTML5模板引擎,可以在Web和非Web环境中使用.它更适合在基于MVC的Web应用程序的视图层提供X ...

  9. Spring Boot 综合示例-整合thymeleaf、mybatis、shiro、logging、cache开发一个文章发布管理系统...

    一.概述 经过HelloWorld示例(Spring Boot 快速入门(上)HelloWorld示例)( Spring Boot  快速入门 详解 HelloWorld示例详解)两篇的学习和练习,相 ...

  10. 模板引擎Thymeleaf(一文让你理解Thymeleaf)

    一.Thymeleaf (一)模板引擎 模板引擎,是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档.使用模板引擎的目的就是为了 ...

最新文章

  1. phonegap+emberjs+python手机店发展,html5实现本地车类别~
  2. MySql 密码忘记了,不用重装
  3. 监管发文:规范大学生群体消费贷款,避免陷入消费贷款陷阱
  4. mysql实现树形_Mysql实现树形递归查询
  5. 如何更改vs默认调试浏览器
  6. Duilib教程-HelloDuilib及DuiDesigner的简单使用
  7. 32位hex转浮点 python_python——int()、hex()、oct()、bin()、float()数值类型转换函数
  8. 一年中所有节日的排列顺序_计数问题(二)-排列组合的使用
  9. urllib库的使用
  10. Postman: Test
  11. 域控制器诊断工具 (dcdiag.exe)
  12. 基于Android的手机邮件收发(JavaMail)之四(邮件的发送)
  13. 卡巴斯基网络安全解决方案-服务器虚拟化安全2.0安装方法,卡巴斯基网络安全解决方案-协作服务器.PDF...
  14. npm 可视化html编辑器,Vue + element从零打造一个H5页面可视化编辑器——pl-drag-template...
  15. ue4蓝图碰撞检测的类型_UE4蓝图碰撞检测解析
  16. 饮用水公司配送管理系统可行性报告
  17. 定位篇align_measurements
  18. C语言经典实例003:输出名言
  19. 基于RPA的自动化测试研究
  20. java宠物商店管理系统_Java实现宠物商店管理系统

热门文章

  1. 诺奖10年,干细胞领域再突破!华大单细胞技术助力获得人类体外诱导全能干细胞...
  2. 后香农时代,华为提出10大数学挑战问题
  3. 美国在人工智能领域亟待解决的5大难题
  4. 《自然》:修复AI神经网络的缺陷
  5. Nature新研究:猪脑死亡4小时后,科学家成功恢复脑细胞功能
  6. 智能的源泉,大脑从何而来?
  7. 为什么我们总认为开源不挣钱?
  8. 我为什么最终放弃了 Linux 桌面版的研发
  9. 程序员,你得一条道走到黑!
  10. 人均 11878 元,2020 年研发岗年终奖最高!技术、产品岗均榜上有名