thymeleaf
一. 简要:
thymeleaf 支持html5标准;是一种模板引擎框架(TemplateEngine Framework);thymeleaf 页面无须部署到servlet开发到服务器上,直接通过浏览器就能打开。它可以完全替代 JSP 。特点:
1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
2.它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果。
3.Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
二. thymeleaf 标准表达式语法
1. 简单表达式
(1) Variable Expressions(变量表达式):${…}。
EX: ${session.user.name}
它们将以HTML标签的一个属性来表示:
<span th:text="${book.author.name}">
<li th:each="book : ${books}"> 变量表达式可以是OGNL表达式或Spring EL表达式。
<span th:text="${book.author.name}">
<li th:each="book : ${books}">
这里${books}从上下文中选择名为books的变量,并将其评估为可在th:each循环中使用的迭代器(iterable)
e.g.
1.Established locale country: <spanth:text="${#locale.country}">US</span>
2.<p> Today is: <spanth:text="${#calendars.format(today,'ddMMMMyyyy')}">13 May 2011</span></p>
(2) Selection Expressions(选择表达式):*{…}。
EX: *{customer.name}
(所有可用值表达式:比如*{name} 从可用值中查找name,如果有上下文,比如上层是object,则查object中的name属性。)
所作用的对象由th:object属性指定。
EX:
equals:(等价于)
(3) Message(il8n)Expressions(消息表达式):#{…}。
文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用Key索引Value,还可以提供一组参数(可选).
国际化时使用,也可以使用内置的对象,比如date格式化数据
EX:
<table>
...
<th th:text="#{header.address.city}">...</th>
<th th:text="#{header.address.country}">...</th>
...
</table>
#{main.title}
#{message.entrycreated(${entryId})}
注意:如果希望消息key由上下文变量的值确定,或者将变量指定为参数,则可以在消息表达式中使用变量表达式。
(4) Link(URL)Expressions(链接表达式):@{…}。
URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL重写。 @{/order/list}
URL还可以设置参数: @{/order/details(id=${orderId})}
相对路径: @{../documents/report}
EX:
链接表达式可以是相对的,在这种情况下,应用程序上下文将不会作为URL的前缀。
<a th:href=”@{../documents/report}”>…</a>
也可以是服务器相对(同样,没有应用程序上下文前缀)
<a th:href=”@{~/contents/main}”>…</a>
e.g.
<a th:href="@{http://www.thymeleaf/documentation.html}"></a>
equals:
<ahref="http://www.thymeleaf/documentation.html"></a>
<form th:action="@{/createOrder}">
<a href="main.html" th:href="@{/main}">
(5) Fragment Expressions(分段表达式):~{…}。
分段表达式是一种表示标记片段并将其移动到模板周围的简单方法。
最常见的用法是使用th:insert或th:replace插入片段。
2. 字面量
(1) 文本:’one text’ ’Another one!’等。
<divth:class=" ‘the content’ ">...</div>
(2) 数值:0、34、3.0、12.3等。
ex: <p>The year is <spanth:text="2013">1492</span>.</p>
(3) 布尔:true、false。
ex: <divth:if="${user.isAdmin()} == false">
ex: <divth:if="${user.isAdmin() == false}">
(4) null :null。
ex: <divth:if="${variable.something} == null">
(5) Literal Token(字面量标记):one、sometext、main等。
ex:
<div th:class="content">...</div>3. 文本操作
(1) 字符串拼接:+。
(2) 文本替换:| The name is ${name} |。
ex:
<span th:text="|Welcome to our application, ${user.name}!|">
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
<span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|">
4. 算数操作
(1) 二元运算符:+、- 、* 、/、%。
(2) 减号(单目运算符):—。
<ol>
<li>+:<span th:text="1+1">1+1</span>.</li>
<li>-: <span th:text="2-1">2-1</span>.</li>
<li>*:<span th:text="2*3">2*3</span>.</li>
<li>/: <span th:text="9/4">9/4</span>.</li>
<li>%:<span th:text="9%4">9%4</span>.</li>
</ol>
5. 布尔操作
(1) 二元运算符:and、or。
(2) 布尔否定(一元运算符):!、not。
<ol>
<li>and:<span th:if="${!#lists.isEmpty(list)} and ${#lists.isEmpty(list)}" th:text="${!#lists.isEmpty(list)} and ${#lists.isEmpty(list)}">and</span></li>
<li>or:<span th:if="${!#lists.isEmpty(list)} or ${#lists.isEmpty(list)}"
th:text="${!#lists.isEmpty(list)} or ${#lists.isEmpty(list)}">or</span></li>
<li>!(not):<span th:if="${!#lists.isEmpty(list)}"
th:text="${!#lists.isEmpty(list)}">not</span></li>
</ol>
6. 比较和等价
(1) 比较:>、<、>=、<=、(gt,lt,ge,le)。
(2) 等价:==、!=、(eq、ne)。
<ol>
<li>>(gt):<span th:text="1+1" th:if="${#lists.size(list)} > 1">大于></span>else</li>
<li>小于lt:<span th:if="${#lists.size(list)} lt 1">小于</span>else</li>
<li>>=(ge):<span th:if="${#lists.size(list)} >= 1">大于等于>=</span>else</li>
<li>小于等于(le):<span th:if="${#lists.size(list)} le 1">小于等于</span>else</li>
<li>!(not):<span th:if="${!#lists.isEmpty(list)}">!(not)</span>else</li>
<li>==(eq):<span th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')">等于==</span></li>
<li>!=(ne/neq):size:<span th:text="${#lists.size(list)}" th:if="${#lists.size(list)} != 1"></span></li>
</ol>
7. 条件运算符
(1)If-then:(if) ? (then)。
(2)If-then-else:(if) ? (then) : (else)。
(3)Default:(value) ? (default value)。
<li>? 'xx' :'xx'(if ? then:else)<span th:class="${title} ? 'green' :' red'">样例一</span></li>
<li>?'xx'(if ? then)<span th:class="${title1} ? 'green'">样例二</span></li>
8.特殊标记
No-Operation(无操作):_。
9.表达式基本对象(Expression Basic Objects)
(1)#ctx:上下文对象。
(2)#vars: 上下文变量。
(3)#locale:上下文区域设置。
(4)#request:HttpServletRequest对象(仅在Web上下文中)。
(5)#response:HttpServletResponse对象(仅在Web上下文中)。
(6)#session:HttpSession对象(仅在Web上下文中)。
(7)#servletContext:ServletContext对象(仅在Web上下文中)。
10.表达式工具对象(ExpressionUtility Objects)
(1)#execInfo:模板执行的信息。
(2)#message:在变量内获取外部信息的方法表达式,与使用#{…}语法获得的方式相同。
(3)#uris:用于转义URL/URI部分的方法。
(4)#conversions:执行已配置的conversion service。
(5)#numbers:格式化数字对象的方法。
(6)#strings:String对象的方法,包括contains,startsWith,prepending/appending等。
(7)#objects:对象通常方法。
(8)#bools:布尔判断的方法。
(10)#lists:list方法。
(11)#sets:set方法。
(12)#maps:map方法。
(13)#aggregates:在数组或集合上创建聚合的方法。
(14)#ids:用于处理可能重复的id属性的方法(如作为迭代的结果)。
常用th标签都有那些?
| 关键字 | 功能介绍 | 案例 |
|---|---|---|
| th:id | 替换id | <input th:id="'xxx' + ${collect.id}"/> |
| th:text | 文本替换 | <p th:text="${collect.description}">description</p> |
| th:utext | 支持html的文本替换 | <p th:utext="${htmlcontent}">conten</p> |
| th:object | 替换对象 | <div th:object="${session.user}"> |
| th:value | 属性赋值 | <input th:value="${user.name}" /> |
| th:with | 变量赋值运算 | <div th:with="isEven=${prodStat.count}%2==0"></div> |
| th:style | 设置样式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" |
| th:onclick | 点击事件 | th:onclick="'getCollect()'" |
| th:each | 属性赋值 | tr th:each="user,userStat:${users}"> |
| th:if | 判断条件 | <a th:if="${userId == collect.userId}" > |
| th:unless | 和th:if判断相反 | <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> |
| th:href | 链接地址 | <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> /> |
| th:switch | 多路选择 配合th:case 使用 | <div th:switch="${user.role}"> |
| th:case | th:switch的一个分支 | <p th:case="'admin'">User is an administrator</p> |
| th:fragment | 布局标签,定义一个代码片段,方便其它地方引用 | <div th:fragment="alert"> |
| th:include | 布局标签,替换内容到引入的文件 | <head th:include="layout :: htmlhead" th:with="title='xx'"></head> /> |
| th:replace | 布局标签,替换整个标签到引入的文件 | <div th:replace="fragments/header :: title"></div> |
| th:selected | selected选择框 选中 | th:selected="(${xxx.id} == ${configObj.dd})" |
| th:src | 图片类地址引入 | <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" /> |
| th:inline | 定义js脚本可以使用变量 | <script type="text/javascript" th:inline="javascript"> |
| th:action | 表单提交的地址 | <form action="subscribe.html" th:action="@{/subscribe}"> |
| th:remove | 删除某个属性 | <tr th:remove="all"> 1.all:删除包含标签和所有的孩子。2.body:不包含标记删除,但删除其所有的孩子。3.tag:包含标记的删除,但不删除它的孩子。4.all-but-first:删除所有包含标签的孩子,除了第一个。5.none:什么也不做。这个值是有用的动态评估。 |
| th:attr | 设置标签属性,多个属性可以用逗号分隔 | 比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。 |
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-equiv
th: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:wrap
th:vspace th:width th:wrap
th:xmlbase th:xmllang th:xmlspace布尔类型
th:async th:autofocus th:autoplay
th:checked th:controls th:declare
th:default th:defer th:disabled
th:formnovalidate th:hidden th:ismap
th:loop th:multiple th:novalidate
th:nowrap th:open th:pubdate
th:readonly th:required th:reversed
th:scoped th:seamless th:selected
三. thymeleaf设置属性值:
(1)th:text
可对表达式或变量求值,并将结果显示在其被包含的 html标签体内替换原有html文本
文本链接: 用 “+”符号,若是变量表达式也可以用“|”符号.
(2)th:utext
e.g.
若home.welcome=Welcome to our <b>fantastic</b> grocery store!
用<p th:text="#{home.welcome}"></p>解析结果为:
<p>Welcome to our <b>fantastic</b> grocery store!</p>
解决方案
<p th:utext="#{home.welcome}"></p>即可。
等效于<p>Welcome to our <b>fantastic</b> grocery store!</p>
(3)th:href
@{xxx} :链接url的表达式
th: attr 用于设置任意属性。
th: value用于设置value属性值。
th:action设置action属性。
2. 同时设置多个值
th:alt-title用于设置alt和title。
th:lang-xmllang用于设置lang和xml:lang。
3. 附加和添加前缀
th:attrappend和th:attrprepend用于附加和添加前缀属性。
4. 固定值布尔属性
四.迭代器(iter)与条件语句
1.th:each将循环array或list中的元素并重复打印一组标签,语法相当于Java foreach表达式。
可以用th:each属性进行遍历的对象如下。
(1) 任何实现Java.util.Iterable的对象。
(2) 任何实现Java.util.Enumeration的对象。
(3) 任何实现Java.util.Iterator的对象,其值将被迭代器返回,而不需要在内存中缓存所有的值。
(4) 任何实现Java.util.Map的对象。迭代映射时,迭代变量将是Java.util.Map.Entry类。
(5) 任何数组。
(6) 任何其他对象将被视为包含对象本身的单值列表。
2.状态变量
提供状态变量来跟踪迭代器状态。
判断操作(实例)
thymeleaf提供了几种判断,if、switch
<table>
<thead>
<th></th>
</thead>
<tbody>
<tr th:each="test:${test}">
<!--判断成绩-->
<td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
<td th:if="${test.Score} ge 60 and ${test.Score} le 70">中</td>
<td th:if="${test.Score} gt 70 and ${test.Score} le 80">良</td>
<td th:if="${test.Score} gt 80 and ${test.Score} le 90">优</td>
<td th:if="${test.Score} gt 90 and ${test.Score} le 100">超级优秀</td>
</tr>
<br>
<tr th:each="test:${test}">
<!--判断成绩 一般只有两种情况的时候可以使用这种方式-->
<td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
<!--除了这些条件之外的-->
<td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td>
</tr>
<tr th:each="test:${test}">
<td th:switch="${test.male}">
<span th:case="1">男</span>
<span th:case="2">女</span>
<!--其他情况-->
<span th:case="*">未知</span>
</td>
</tr>
</tbody>
</table>
结果显示:
差
中
超级优秀
差
及格
及格
男
女
th:each属性中定义如下状态变量。
(1) index属性是当前“迭代器引擎”,从0开始。
(2) count属性是当前“迭代器索引”,从1开始。
(3) size 属性是迭代器元素的总数。
(4) current 是当前“迭代变量”。
(5) even/odd判断当前迭代器是否为even或odd。
(6) first判断当前迭代器是否为第一个。
(7) last判断当前迭代器是否为最后。
3.条件语句
(1)if和unless
支持下列规则判断:
<1>值不为null:
<1.1>布尔类型且为true;
<1.2>非0数字;
<1.3>非0字符;
<1.4>非“false”, “off” or “no”字符串;
<1.5>判断值不为布尔值,数字,字符,字符串
结果为true
<2>值为null,结果为false
(2)switch语句
Switch语句使用th:switch与th:case属性集合来实现。
一旦有一个th:case对应结果为true,其他均为false;
默认值语法为: th:case=”*”
几种常用的使用方法
1、赋值、字符串拼接
<p th:text="${collect.description}">description</p>
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
字符串拼接还有另外一种简洁的写法
<span th:text="|Welcome to our application, ${user.name}!|">
2、条件判断 If/Unless
Thymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中,<a>标签只有在th:if中条件成立时才显示:
<a th:if="${myself=='yes'}" > </i> </a>
<a th:unless=${session.user != null} th:href="@{/login}" >Login</a>
th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。
也可以使用 (if) ? (then) : (else) 这种语法来判断显示的内容
3、for 循环
<tr th:each="collect,iterStat : ${collects}">
<th scope="row" th:text="${collect.id}">1</th>
<td >
<img th:src="${collect.webLogo}"/>
</td>
<td th:text="${collect.url}">Mark</td>
<td th:text="${collect.title}">Otto</td>
<td th:text="${collect.description}">@mdo</td>
<td th:text="${terStat.index}">index</td>
</tr>
渲染列表数据是一种非常常见的场景,例如现在有n条记录需要渲染成一个表格
,该数据集合必须是可以遍历的,使用th:each标签:
<body>
<h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
<p>
<a href="../home.html" th:href="@{/}">Return to home</a>
</p>
</body>可以看到,需要在被循环渲染的元素(这里是)中加入th:each标签,其中th:each=”prod : ${prods}”意味着对集合变量prods进行遍历,循环变量是prod在循环体中可以通过表达式访问。
循环下标判
iterStat称作状态变量,属性有:
- index:当前迭代对象的index(从0开始计算)
- count: 当前迭代对象的index(从1开始计算)
- size:被迭代对象的大小
- current:当前迭代变量
- even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
- first:布尔值,当前循环是否是第一个
- last:布尔值,当前循环是否是最后一个
<th:block th:each="mylist,iterStat:${list}"> 111 <span th:text="${mylist}"></span> <th:block th:if="${iterStat.index le 1}"> <span th:text="${mylist}"></span> </th:block> </th:block>
下拉选择
<select name="subId" id="subId" lay-verify="" >
<option value="">请选择</option>
<option th:each="channelsub:${subchannels}" th:selected="${channelsub.id == subId}" th:value="${channelsub.id}" th:text="${channelsub.name}"></option>
</select>
4、URL
URL在Web应用模板中占据着十分重要的地位,需要特别注意的是Thymeleaf对于URL的处理是通过语法@{…}来处理的。 如果需要Thymeleaf对URL进行渲染,那么务必使用th:href,th:src等属性,下面是一个例子
<!-- Will produce 'http://localhost:8080/standard/unread' (plus rewriting) -->
<a th:href="@{/standard/{type}(type=${type})}">view</a>
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
设置背景
<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>
根据属性值改变背景
<div class="media-object resource-card-image" th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'" ></div>
几点说明:
- 上例中URL最后的
(orderId=${o.id})表示将括号内的内容作为URL参数处理,该语法避免使用字符串拼接,大大提高了可读性 @{...}表达式中可以通过{orderId}访问Context中的orderId变量@{/order}是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为app,那么结果应该是/app/order
5、内联js
内联文本:[[…]]内联文本的表示方式,使用时,必须先用th:inline=”text/javascript/none”激活,th:inline可以在父级标签内使用,甚至作为body的标签。内联文本尽管比th:text的代码少,不利于原型显示。
<script th:inline="javascript">
/*<![CDATA[*/
...
var username = /*[[${sesion.user.name}]]*/ 'Sebastian';
var size = /*[[${size}]]*/ 0;
...
/*]]>*/
</script>
js附加代码:
/*[+
var msg = 'This is a working application';
+]*/
js移除代码:
/*[- */
var msg = 'This is a non-working template';
/* -]*/
6、内嵌变量
为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问:
下面用一段代码来举例一些常用的方法:
dates
- dates : java.util.Date的功能方法类。
- calendars : 类似#dates,面向java.util.Calendar
- numbers : 格式化数字的功能方法类
- strings : 字符串对象的功能类,contains,startWiths,prepending/appending等等。
- objects: 对objects的功能类操作。
- bools: 对布尔值求值的功能方法。
- arrays:对数组的功能类方法。
- lists: 对lists功能类方法
- sets
- maps
…
/*
* Format date with the specified pattern
* Also works with arrays, lists or sets
*/
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
/*
* Create a date (java.util.Date) object for the current date and time
*/
${#dates.createNow()}
/*
* Create a date (java.util.Date) object for the current date (time set to 00:00)
*/
${#dates.createToday()}
/*
* Check whether a String is empty (or null). Performs a trim() operation before check
* Also works with arrays, lists or sets
*/
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}
/*
* Check whether a String starts or ends with a fragment
* Also works with arrays, lists or sets
*/
${#strings.startsWith(name,'Don')} // also array*, list* and set*
${#strings.endsWith(name,endingFragment)} // also array*, list* and set*
/*
* Compute length
* Also works with arrays, lists or sets
*/
${#strings.length(str)}
/*
* Null-safe comparison and concatenation
*/
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}
/*
* Random
*/
${#strings.randomAlphanumeric(count)}
五.thymeleaf模板片段
1.定义和引用片段
(1)定义片段属性用: th:fragment
fragment片段定义语法:
如th:fragment=”copy”这样就定义了一个名为copy的fragment.
模板操作
主要引入公共头部和底部相关代码使用 ,当然也可以其他地方使用
- 示例
底部模板代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<body>
<div th:fragment="footer">
© 2016 xxx
</div>
</body>
</html>Springboot整合引入模块
<!--写入绝对路径即可引入 -->
<div th:include="/back/import/footer :: footer"></div>
th:include:将fragment的内容包含进来;
th:replace:用fragment替换掉所在标签
(2)引用片段 th:insert或 th:replace 属性
(3)th:include 类似于th:insert 但不是插入片段,它只插入此片段的”内容“。
注:th:insert 需要一个”片段表达式”(~{…})
th:remove
一般用于将模拟数据在真实环境中移除:
<1>all-移除标签及标签内容
<2>body-只移除内容
<3>tag-只移除所在标签
<4>all-but-first-除第一条外移除所有内容
<5>none-donothing.
th:width
定义局部变量
1.可一次定义多个,逗号分隔
外围包裹–block
有时候需要在代码外部加层条件,但写div之类的又影响样式,此情况下你可以用下面这种方式:
<th:block th:with="score=${test.Score}">
<td th:if="${score} ge 60">及格啦</td>
</th:block>使用thymeleaf布局
使用thymeleaf布局非常的方便
定义代码片段
<footer th:fragment="copy">
© 2016
</footer>
在页面任何地方引入:
<body>
<div th:include="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
</body>
th:include 和 th:replace区别,include只是加载,replace是替换
返回的HTML如下:
<body>
<div> © 2016 </div>
<footer>© 2016 </footer>
</body>
下面是一个常用的后台页面布局,将整个页面分为头部,尾部、菜单栏、隐藏栏,点击菜单只改变content区域的页面
<body class="layout-fixed">
<div th:fragment="navbar" class="wrapper" role="navigation">
<div th:replace="fragments/header :: header">Header</div>
<div th:replace="fragments/left :: left">left</div>
<div th:replace="fragments/sidebar :: sidebar">sidebar</div>
<div layout:fragment="content" id="content" ></div>
<div th:replace="fragments/footer :: footer">footer</div>
</div>
</body>
任何页面想使用这样的布局值只需要替换中见的 content模块即可
<html xmlns:th="http://www.thymeleaf.org" layout:decorator="layout">
<body>
<section layout:fragment="content">
...
也可以在引用模版的时候传参
<head th:include="layout :: htmlhead" th:with="title='Hello'"></head>
layout 是文件地址,如果有文件夹可以这样写 fileName/layout:htmlhead
htmlhead 是指定义的代码片段 如 th:fragment="copy"
六.表达式基本对象
1.基本对象
(1)#ctx:上下文对象。
(2)#locale:直接访问与java.util.Locale关联的当前的请求。
2.web上下文命名空间
(1)param:用于检索请求参数。
(2)session:用于检索会话属性。
(3)application:用于检索应用及上下文属性。
3.web上下文对象
(1)#request:直接访问与当前请求关联的javax.servlet.http.HttpServletRequest对象。
(2)#session:直接访问与当前请求关联的javax.servlet.http.HttpSession对象。
(3)#servletContext:直接访问与当前请求关联的javax.servlet.ServletContext对象。
七.模板注释
1.标准 HTML/XML注释
语法:<!-- -->
2.解析器级注释块(Parser-level comment blocks)
语法:<!--/* */-->
thymeleaf解析时会移除代码
单行:<!--/* xxxxx */-->
双行:
<!--/*-->
Xxxxxx
Xxxxxx
<!--*/-->
3.针对原型的注释
语法:<!--/*/ /*/-->
thymealeaf解析时会移除掉此标签对,但不会移除其中的内容。
4.与th:block结合
thymealeaf解析时会移除掉此标签对,但不会移除其中的内容。
内联
[[...]]是内联文本的表示格式,但需要使用th:inline属性(分为text,javascript,none)激活.
1.文本内联
<pth:inline="text">Hello, [[${session.user.name}]]!</p>
2.脚本内联
<scriptth:inline="javascript">
/*<![CDATA[*/
...
varusername = /*[[${session.user.name}]]*/ 'Sebastian';
...
/*]]>*/
</script>
Note:
1.脚本注释/* */中的内容会在浏览器端静态打开页面时被忽略;
2.thymeleaf解析模板时会把后面的文本'Sebastian'移除.
javascript内联时特性
<1>javascript附加代码
语法:/*[+ +]*/
/*[+
var msg = 'This is a working application';
+]*/
<2>javascript移除代码
语法:/*[- */ /* -]*/
/*[- */
var msg = 'This is a non-working template';
/* -]*/