[转载]Thymeleaf参考手册

转载自 http://blog.csdn.net/zrk1000/article/details/72667478

1、创建 html

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

    另外:xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout".

    th:* attributes : 

    layout:* attributes
注意:html 中的标签必须严格规范,标签必须闭合,即<div />技术或者</div>类似结束

2、使用文本

语法 说明
{home.welcome} 使用国际化文本,国际化传参直接追加(value…)
${user.name} 使用会话属性
@{} <link rel="stylesheet" type="text/css" media="all"href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
${} 中预存对象(表达式中基本对象)
param 获取请求参数,比如${param.name},http://localhost:8080?name=jeff
session 获取 session 的属性
application 获取 application 的属性
execInfo 有两个属性 templateName和 now(是 java 的 Calendar 对象)
ctx
vars
locale
httpServletRequest
httpSession
th扩展标签
th:text 普通字符串
th:utext 转义文本
th:href
th:attr <img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
th:with 定义常量
th:attrappend
th:classappend
th:styleappend

其他th标签

* * *
th:abbr th:accept th:accept-charset
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:frame
th:frameborder th:headers th:height
th:high th:href th:hreflang
th:hspace th:http-equiv th:icon
th:id 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: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:xmlbase
th:xmllang th:xmlspace th:alt-title 或th:lang-xmllang(如果其中两个属性值相同)

对于 html5 元素名称的另一种友好写法

<table>
    <tr data-th-each="user : ${users}">
    <td data-th-text="${user.login}">...</td>
    <td data-th-text="${user.name}">...</td> </tr>
</table>

3、表达式语法

1、简单表达式语法

  • #{...} : Message 表达式
<p th:utext="#{home.welcome(${session.user.name})}"> Welcome to our grocery store, Sebastian Pepper!</p>
<p th:utext="#{${welcomeMsgKey}(${session.user.name})}"> Welcome to our grocery store, Sebastian Pepper!</p> 
  • ${}:变量表达式
ongl标准语法,方法也可以被调用
  • *{} :选择变量表达式
<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text={nationality}">Saturn</span>.</p>
</div> 
等价于
<div>
    <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> 
    <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>
当然了,这两者可以混合使用
还有一种方式
<div>
    <p>Name: <span th:text="*{session.user.name}">Sebastian</span>.</p> 
    <p>Surname: <span th:text="*{session.user.surname}">Pepper</span>.</p> 
    <p>Nationality: <span th:text="*{session.user.nationality}">Saturn</span>.</p>
</div>  
  • @{}: 链接 URL 表达式
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --> <a href="details.html"

th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->

<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->

<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

2、变量

分类 示例
文本 ‘one text’ , ‘Another one!’ ,…
数字 0 , 34 , 3.0 , 12.3 ,…
真假 true , false
文字符号 one , sometext , main ,…

3、字符连接

分类 示例
+ ‘The name is ‘+${name}
The name is ${name}

4、 算数运算

语法 示例
+, -, *, /, % 二元运算符
- 减号(一元运算符)

5、 真假运算

分类 示例
and , or 二元运算符
! , not 否定(一元运算符)

6、比较运算

分类 示例
>, <, >=, <= (gt, lt, ge, le) 比较
== , != ( eq , ne ) 平等

7、 条件运算

分类 示例
if-then (if) ? (then)
if-then-else (if) ? (then) : (else)
Default (value) ?: (defaultvalue)

综合示例:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

4、表达式中使用内置对象

#dates :

utility methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects.

#numbers :
utility methods for formatting numeric objects.

#strings : 
utility methods for String objects: contains, startsWith, prepending/appending, etc. #objects : utility methods for objects in general.

#bools : 
utility methods for boolean evaluation. #arrays : utility methods for arrays.

#lists :
utility methods for lists.

#sets : 
utility methods for sets.

#maps : 
utility methods for maps.

#aggregates : 
utility methods for creating aggregates on arrays or collections.

#messages : 
utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{...} syntax.

#ids : 
utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

5、预处理

__${expression}__

6、循环

<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>

迭代器的状态
index: 当前的索引,从0开始
count: 当前的索引,从1开始
size:总数
current:
even/odd:
first
last
<table> 
    <tr>
        <th>NAME</th>
        <th>PRICE</th>
        <th>IN STOCK</th>
    </tr>
    <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <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>

7、判断


if

<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>

unless

<a href="comments.html" th:href="@{/comments(prodId=${prod.id})}" th:unless="${#lists.isEmpty(prod.comments)}">view</a>

switch

<div th:switch="${user.role}">
    <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p>
</div>

<div th:switch="${user.role}">
    <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> <p th:case="*">User is some other thing</p>
</div>

8、模板布局

th:fragment

示例

templates/footer.html

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"
    <body>
         <div th:fragment="copy">
            © 2011 The Good Thymes Virtual Grocery
         </div>
    </body>
</html>

templates/index.html中使用

    <body> ...
        <div th:include="footer :: copy"></div> 
    </body>

或者
    ...
    <div id="copy-section">
        © 2011 The Good Thymes Virtual Grocery 
    </div>
    ...

使用

    <body> ...
        <div th:include="footer :: #copy-section"></div>
    </body>

th:include 和 th:replace 区别

th:include 加入代码

th:replace 替换代码

模板传参:参数传递顺序不强制

    定义

<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>

    使用

<div th:include="::frag (${value1},${value2})">...</div>

<div th:include="::frag (onevar=${value1},twovar=${value2})">...</div> 
等价于 <div th:include="::frag" th:with="onevar=${value1},twovar=${value2}">)

9、移除标签 th:remove

取值范围

  • all:移除所有

  • body:不移除自己,但移除他的子标签

  • tag: 只移除自己,不移除他的子标签

  • all-but-first:移除所有内容除第一个外

  • none:啥都不做

10、执行顺序

这里写图片描述

11、thymeleaf注释语法

  • html 看不到,并且 thymeleaf 不会执行
<!--/* This code will be removed at thymeleaf parsing time! */-->
  • and 未运行可以在 html 中看到,运行后就消失
<!--/*-->
   <div>you can see me only before thymeleaf processes me! </div>
<!--*/-->
  • 运行后才会看到
<span>hello!</span>
<!--/*/
<div th:text="${true}">...</div>
/*/-->
<span>goodbye!</span>

12、th:block 的使用

<table>
    <th:block th:each="user : ${users}">
    <tr>
        <td th:text="${user.login}">...</td> <td th:text="${user.name}">...</td>
    </tr>
    <tr>
        <td colspan="2" th:text="${user.address}">...</td> 
    </tr>
    </th:block>
</table>

推荐下面写法(编译前看不见)

<table>
    <tr>
        <td th:text="${user.login}">...</td>
        <td th:text="${user.name}">...</td> </tr>
        <tr>
        <td colspan="2" th:text="${user.address}">...</td>
    </tr>
    <!--/*/ </th:block> /*/--> 
</table>

13、文本内联th:inline

th:inline 可以等于 text , javascript(dart) , none

  • text: [[…]]
<p th:inline="text">Hello, [[#{test}]]</p>
  • javascript: /[[…]]/
<script th:inline="javascript">
    var username = /*[[
        #{test}
    ]]*/;
    var name = /*[[
        ${param.name[0]}+${execInfo.templateName}+'-'+${#dates.createNow()}+'-'+${#locale}
    ]]*/;
</script>
<script th:inline="javascript">

/*<![CDATA[*/

    var username = [[#{test}]];

    var name = [[${param.name[0]}+${execInfo.templateName}+'-'+${#dates.createNow()}+'-'+${#locale}]];

/*]]>*/

</script>
  • adding code: /* [+…+]*/
var x = 23;
/*[+
var msg = 'Hello, ' + [[${session.user.name}]]; +]*/
var f = function() {
...
  • removind code: /[- / and /* -]*/
var x = 23;
/*[- */
var msg = 'This is a non-working template'; /* -]*/
var f = function() {
...

14、验证模板的正确性

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-transitional-thymeleaf-4.dtd">
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-frameset-thymeleaf-4.dtd">
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml11-thymeleaf-4.dtd">

15、特殊用法展示

<td th:text="${#aggregates.sum(o.orderLines.{purchasePrice * amount})}">23.32</td>

以上表示List orderLines的所有订单的总价

附件A: 基础对象

ctx:对应org.thymeleaf.spring[3|4].context.SpringWebContext

/*
* ======================================================================
* See javadoc API for class org.thymeleaf.context.IContext
* ====================================================================== */
${#ctx.locale} ${#ctx.variables}
/*
* ======================================================================
* See javadoc API for class org.thymeleaf.context.IWebContext
* ====================================================================== */
${#ctx.applicationAttributes} 
${#ctx.httpServletRequest} 
${#ctx.httpServletResponse} 
${#ctx.httpSession} 
${#ctx.requestAttributes} 
${#ctx.requestParameters} 
${#ctx.servletContext} 
${#ctx.sessionAttributes}

locale: 对应java.util.Locale

vars: 对应 org.thymeleaf.context.VariablesMap

/*
* ====================================================================== * See javadoc API for class org.thymeleaf.context.VariablesMap
* ====================================================================== */
${#vars.get('foo')} 
${#vars.containsKey('foo')} 
${#vars.size()}
...

param

${param.foo} 是一个 String[] 如果要获取需要${param.foo[0]}

/*
* ============================================================================ * See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap * ============================================================================ */
${param.foo} // Retrieves a String[] with the values of request parameter 'foo' 
${param.size()}
${param.isEmpty()}
${param.containsKey('foo')}
...

session

application

httpServletRequest

themes : as JSP tag spring:theme

Spring Beans 的访问

<div th:text="${@authService.getUserName()}">...</div>

附件B:工具对象

  • dates See javadoc API for class org.thymeleaf.expression.Dates

  • calendars See javadoc API for class org.thymeleaf.expression.Calendars

  • numbers See javadoc API for class org.thymeleaf.expression.Numbers

  • strings See javadoc API for class org.thymeleaf.expression.Strings

  • objects See javadoc API for class org.thymeleaf.expression.Objects

  • bools See javadoc API for class org.thymeleaf.expression.Bools

  • arrays See javadoc API for class org.thymeleaf.expression.Arrays

  • lists See javadoc API for class org.thymeleaf.expression.Lists

  • sets See javadoc API for class org.thymeleaf.expression.Sets

  • maps See javadoc API for class org.thymeleaf.expression.Maps

  • aggregates See javadoc API for class org.thymeleaf.expression.Aggregates

  • messages See javadoc API for class org.thymeleaf.expression.Messages

  • ids See javadoc API for class org.thymeleaf.expression.Ids

附件C:DOM 选择器语法

DOM选择器借语法功能从XPath,CSS和jQuery,为了提供一个功能强大且易于使用的方法来指定模板片段

<div th:include="mytemplate :: [//div[@class='content']]">...</div>
<div th:include="mytemplate :: [div.content]">...</div>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,679评论 6 342
  • 不知从什么时候起,人与自己的关系,变冷了。 王晶晶说,以前她在街上闲逛,看到路人只是在盯着地板在走路。现在外出碰到...
    五月爱花阅读 1,446评论 9 4
  • 小山脚下,有座砖瓦房,成串的玉米挂在横梁上。墙上的红辣椒,和金黄的玉米错落排布,洋溢着浓郁的乡村气息。火热的炕,篱...
    侯玲玉阅读 463评论 0 3
  • 今日反省一事 六月初信誓旦旦的说给呵宝戒掉白天用纸尿裤,并在谢先生面前保证一星期肯定成功戒掉,可是这都一个多月了还...
    有一个棉袄阅读 198评论 0 0