thymeleaf参考手册

摘要:
)${user.name}使用会话属性@{}--${}中预先存储的对象参数获取请求参数,例如${param.name},http://localhost:8080?name=jeffsession获取会话应用程序的属性获取应用程序execInfo的属性有两个属性templateName和nowctxvarslocalehttpServletRequesthttpSession––th扩展标记th:text普通字符串th:utext Escape文本th:href:attrth:with定义常量th:attrappendth:classappendth:styleappend其他th标记h:codebase:codetype:ccolst:colspanth:compact:contentth:content-itableth:contextmuth:datath:datetimeth:dirth:draggableth:dropzoneth:enctypeth:forth:formth:formactionth:formencypeth:formmethodth:formtargetth:frameth:frameborderth:headersth:heightth:hightth:highth:hrefth:hreflangth:hspaceth:http-equidith:ico第n个:宽度:键类型:种类:标签:长度:列表:长度:长度:宽度:长度:外观:长度:边缘宽度:最大长度:中间长度:方法:最小长度:名称:最佳长度:模式:占位符:后移:预加载:无线组:相对位置:相对位置(relth):行(rowth):规则(rule th):沙盒(sandbox th):范围(scopeth):滚动长度:大小(size th):大小(sizeth):跨度(span th):拼写检查(spellcheckth):srcth:srclangth:待机位置:开始:步骤:styleth th:summaryth:tabindexth:targeth th:title:type th:usemapth:valueth th:valuetypeth:vspaceth:wi widthth:wrap:xmlbaseth:xmllangth:xmlspaceth:alt titleth或th:lang xmllang另一种友好的编写方法<table><trdata th each=“user:${user}”><tddata th text=“${user.login}”˃…</td><tddatath text=”${user.name}“>…</td˃˂/tr></table>123453,表达式语法1,简单表达式语法#{…}:消息表达式欢迎使用我们的词汇表,Sebastian Pepper!
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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
注意:html 中的标签必须严格规范,标签必须闭合,即<div />技术或者</div>类似结束
  • 1
  • 2
2、使用文本
语法说明
{home.welcome}使用国际化文本,国际化传参直接追加(value…)
${user.name}使用会话属性
@{}<link rel="stylesheet" type="text/css" media="all"href="http://t.zoukankan.com/css/gtvg.css" th:href="http://t.zoukankan.com/@{/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="http://t.zoukankan.com/images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
th:with定义常量
th:attrappend 
th:classappend 
th:styleappend 

其他th标签

***
th:abbrth:acceptth:accept-charset
th:abbrth:acceptth:accept-charset
th:accesskeyth:actionth:align
th:altth:archiveth:audio
th:autocompleteth:axisth:background
th:bgcolorth:borderth:cellpadding
th:cellspacingth:challengeth:charset
th:citeth:classth:classid
th:codebaseth:codetypeth:cols
th:colspanth:compactth:content
th:contenteditableth:contextmenuth:data
th:datetimeth:dirth:draggable
th:dropzoneth:enctypeth:for
th:formth:formactionth:formenctype
th:formmethodth:formtargetth:frame
th:frameborderth:headersth:height
th:highth:hrefth:hreflang
th:hspaceth:http-equivth:icon
th:idth:keytypeth:kind
th:labelth:langth:list
th:longdescth:lowth:manifest
th:marginheightth:marginwidthth:max
th:maxlengthth:mediath:method
th:minth:nameth:optimum
th:patternth:placeholderth:poster
th:preloadth:radiogroupth:rel
th:revth:rowsth:rowspan
th:rulesth:sandboxth:scheme
th:scopeth:scrollingth:size
th:sizesth:spanth:spellcheck
th:srcth:srclangth:standby
th:startth:stepth:style
th:summaryth:tabindexth:target
th:titleth:typeth:usemap
th:valueth:valuetypeth:vspace
th:widthth:wrapth:xmlbase
th:xmllangth:xmlspaceth: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>
  • 1
  • 2
  • 3
  • 4
  • 5
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> 
  • 1
  • 2
  • ${}:变量表达式
ongl标准语法,方法也可以被调用
  • 1
  • *{} :选择变量表达式
<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>  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • @{}: 链接 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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'))
  • 1
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).
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
5、预处理
__${expression}__
  • 1
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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
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}">)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
9、移除标签 th:remove

取值范围

  • all:移除所有

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

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

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

  • none:啥都不做

10、执行顺序

这里写图片描述

11、thymeleaf注释语法
  • html 看不到,并且 thymeleaf 不会执行
<!--/* This code will be removed at thymeleaf parsing time! */-->
  • 1
  • and 未运行可以在 html 中看到,运行后就消失
<!--/*-->
   <div>you can see me only before thymeleaf processes me! </div>
<!--*/-->
  • 1
  • 2
  • 3
  • 运行后才会看到
<span>hello!</span>
<!--/*/
<div th:text="${true}">...</div>
/*/-->
<span>goodbye!</span>
  • 1
  • 2
  • 3
  • 4
  • 5
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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
13、文本内联th:inline

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

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

/*<![CDATA[*/

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

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

/*]]>*/

</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • adding code: /* [+…+]*/
var x = 23;
/*[+
var msg = 'Hello, ' + [[${session.user.name}]]; +]*/
var f = function() {
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • removind code: /[- / and /* -]*/
var x = 23;
/*[- */
var msg = 'This is a non-working template'; /* -]*/
var f = function() {
...
  • 1
  • 2
  • 3
  • 4
  • 5
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">
  • 1
  • 2
  • 3
  • 4
15、特殊用法展示
<td th:text="${#aggregates.sum(o.orderLines.{purchasePrice * amount})}">23.32</td>
  • 1

以上表示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}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

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()}
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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')}
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

session

application

httpServletRequest

themes : as JSP tag spring:theme

Spring Beans 的访问

<div th:text="${@authService.getUserName()}">...</div>
  • 1
附件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>
  • 1
<div th:include="mytemplate :: [div.content]">...</div>

免责声明:文章转载自《thymeleaf参考手册》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇openpyxl 模块的使用浏览器的F5和Ctrl+F5下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

XSS攻击原理、示例和防范措施 --

XSS攻击 XSS(Cross-Site Scripting,跨站脚本)攻击历史悠久,是危害范围非常广的攻击方式。 Cross-Site Stripting的缩写本应该是CSS,但是为了避免和Cascading style sheets(层叠样式表)的缩写混淆,所以将Cross(即交叉)使用交叉形状的X表示。 攻击原理 XSS是注入攻击的一种,攻击者通过将...

CSS对各个浏览器兼容技巧HACK技巧

*   ie6和ie7都可以识别_   只有ie6可以识别\0  只有ie8可以识别:root 只有ie9可以识别  关于CSS对各个浏览器兼容已经是老生常谈的问题了, 网络上的教程遍地都是.以下内容没有太多新颖, 纯属个人总结, 希望能对初学者有一定的帮助. 一、CSS HACK HACK概念: 不同的浏览器,比如Internet Explorer 6,...

五:HttpServletResponse对象

一、HttpServletResponse对象介绍 HttpServletResponse对象代表服务器的响应。这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。查看HttpServletResponse的API,可以看到这些相关的方法。 1.1、负责向客户端(浏览器)发送数据的相关方法    1.2、负责向客户端(浏览器)发送响应头的相...

vue指令(3)v-html

理论知识 v-html可向元素中插入html片段,例如 '< h1>标题一< /h1>'等 该指令存在安全漏洞,因此在本地代码中可以使用,如果要调用第三方的代码中包含该指令,则存在安全隐患。 该指令的值可以同vue对象的data属性中变量绑定。 实践 <!DOCTYPE html> <html> <...

译文:前端性能的重要性 The Importance of Frontend Performance

欢迎訪问我的主页。最新的文章我会首先公布在个人主页上: http://blog.guaidm.com/shocky/ 原书下载地址:http://pan.baidu.com/s/1pJocRwB        在我的web开发生涯里,大部分时候我都是作为一个后台project师。这样一来,我投入了非常多的精力去研究、练习怎样通过后台优化来提升项目产品...

jmeter 查看结果树之查看响应的13种方法

查看结果树查看响应有哪几种方法,可通过左侧面板底部的下拉框选择 1 Text 查看结果树中请求的默认格式为Text,显示取样器结果、请求、响应数据3个部分内容。 取样器结果:默认Raw展示,可以切换为Parsed视图,表单展示更直观。 请求:默认Raw展示,包括Restquest Body 及Restquest Headers两部分。 HTTP视图展示更...