Themeleaf的使用

来源:互联网 发布:淘宝分销怎么赚钱 编辑:程序博客网 时间:2024/06/10 11:49
<div class="col-sm-9">    <div th:switch="${channel.enable}">        <p th:case="'1'">            <input id="enable" name="enable" type="radio"                   class="ace" value="1" checked="checked" />            <span class="lbl">启用</span>            <input id="enable1" name="enable" type="radio"                   class="ace" value="0" />            <span class="lbl">停用</span>        </p>        <p th:case="'0'">            <input id="enable2" name="enable" type="radio"                   class="ace" value="1" />            <span class="lbl">启用</span>            <input id="enable3" name="enable" type="radio"                   class="ace" value="0" checked="checked" />            <span class="lbl">停用</span>        </p>    </div>

</div>

四、标准表达式语法

· 简单表达式 (simple expressions)

  ${...}  变量表达式

  *{...}  选择变量表达式

  #{...}  消息表达式

  @{...}  链接url表达式

· 字面量

  'one text','another one!',...   文本

  0,34,3.0,12.3,... 数值

  true false 布尔类型

  null 空

one,sometext,main 文本字符

· 文本操作

  +  字符串连接

  |The name is ${name}|  字符串连接

· 算术运算

  + , - , * , / , %  二元运算符

  -  负号(一元运算符)

· 布尔操作

  and,or  二元操作符

  !,not 非(一元操作符)

· 关系操作符

  > , < , >= , <= (gt , lt , ge , le)

  == , != (eq, ne)

· 条件判断

(if) ? (then)      if-then

(if) ? (then) : (else)   if-then-else  

<tr th:class="${row.even}? 'even' : 'odd'">  ...</tr>

 

条件表达式中的三个部分自身也可以是表达式,也可以是变量(${...}, *{...}), 消息(#{...}), URL (@{...}) 或字面量 ('...')
条件表达式也可以使用括号来嵌套:

<tr th:class="${row.even}? (${row.first}? 'first' : 'even') : 'odd'">...</tr>

else表达式也可以省略,当条件为false时,会返回null:

<tr th:class="${row.even}? 'alt'">...</tr>

 

(value) ?: (defaultvalue)   Default

只有在第一个表达式返回null时,第二个表达式才会运算

·表达式工具对象

  • #dates 与java.util.Date对象的方法对应,格式化、日期组件抽取等等
  • #calendars 类似#dates,与java.util.Calendar对象对应
  • #numbers 格式化数字对象的工具方法
  • #strings 与java.lang.String对应的工具方法:contains、startsWith、prepending/appending等等
  • #objects 用于对象的工具方法
  • #bools 用于布尔运算的工具方法
  • #arrays 用于数组的工具方法
  • #lists 用于列表的工具方法
  • #sets 用于set的工具方法
  • #maps 用于map的工具方法
  • #aggregates 用于创建数组或集合的聚合的工具方法
  • #messages 用于在变量表达式内部获取外化消息的工具方法,与#{…}语法获取的方式相同
  • #ids 用于处理可能重复出现(例如,作为遍历的结果)的id属性的工具方法

·链接URL
URL在web模板中是一级重要元素,使用@{…}表示

URL的类型:

  绝对URL:

  • http://www.thymeleaf.org

  相对URL:

  • 页面相对: user/login.html
  • 上下文相对:/itemdetails?id=3 (服务器上下文名称会被自动添加)
  • 服务器相对:~/billing/processInvoice(允许调用同一服务器上的另一个上下文中的URL)
  • 协议相对://code.jquery.com/jquery-2.0.3.min.js

Thymeleaf在任何情况下都可以处理绝对URL,对于相对URL,则需要使用一个实现了IWebContext接口的上下文对象,这个对象包含了来自HTTP请求的信息,这些信息用于创建相对链接。

复制代码
<!-- 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>
复制代码

 

· 预处理
Thymeleaf提供预处理表达式的功能。

它是在表壳式正常执行前执行的操作,允许修改最终将要被执行的表达式。

预处理表达式跟正常的一样,但被两个下划线包围住,例如:__${expression}__

假设有一个i18n消息文件Message_fr.properties,里面有一个条目包含了一个调用具体语言的静态方法的OGNL表达式:

article.text=@myapp.translator.Translator@translateToFrench({0})

Messages_es.properties中的等价条目:

article.text=@myapp.translator.Translator@translateToSpanish({0})

可以根据locale先创建用于运算表达式的标记片段,本例中,先通过预处理选择表达式,然后让Thymeleaf处理这个选择出来的表达式:

<p th:text="${__#{article.text('textVar')}__}">Some text here...</p>

对于locale为French的情况,上面的表达式经过预处理后,得出的等价物如下:

<p th:text="${@myapp.translator.Translator@translateToFrench(textVar)}">Some text here...</p>

 

五、 设置属性值
th:attr 任何属性值

<form action="subscribe.html" th:attr="action=@{/subscribe}">  <fieldset>    <input type="text" name="email" />    <input type="submit" value="Subscribe me!" th:attr="value=#{subscribe.submit}"/>  </fieldset></form>

多个属性一起设置,用逗号隔开

<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

设置指定属性

复制代码
th:abbr th:accept th:accept-charsetth:accesskey th:action th:alignth:alt th:archive th:audioth:autocomplete th:axis th:backgroundth:bgcolor th:border th:cellpaddingth:cellspacing th:challenge th:charsetth:cite th:class th:classid ...
复制代码
<input type="submit" value="Subscribe me!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}">
<li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>

 

设置多个属性在同一时间  有两个特殊的属性可以这样设置: th:alt-title 和 th:lang-xmllang

th:alt-title 设置 alt 和 title 
th:lang-xmllang 设置 lang 和 xml:lang 

复制代码
<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" /><img src="../../images/gtvglogo.png"th:src="@{/images/gtvglogo.png}" th:title="#{logo}" th:alt="#{logo}" /><img src="../../images/gtvglogo.png"th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" />
复制代码

 

前置和后置添加属性值  th:attrappend 和 th:attrprepend

<input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />

编译后:

<input type="button" value="Do it!" class="btn warning" />

 

还有两个特定的添加属性 th:classappend 和 th:styleappend

<tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'">

修复的布尔属性

<input type="checkbox" name="active" th:checked="${user.active}" />

所有修复的布尔属性:

复制代码
|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 |
复制代码

HTML5友好的属性及元素名

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

data-{prefix}-{name}是编写Html5自定义属性的标准语法,不需要开发者使用th:*这样的命名空间,Thymeleaf让这种语法自动对所有dialect都可用。

六、遍历

·基础

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

可遍历的对象:实现Java.util.Iterable、java.util.Map(遍历时取java.util.Map.Entry)、array、任何对象都被当作只有对象自身一个元素的列表

·状态

  • 当前遍历索引,从0开始,index属性
  • 当前遍历索引,从1开始,count属性
  • 总元素数量,size属性
  • 每一次遍历的iter变量,current属性
  • 当前遍历是even还是odd,even/odd布尔属性
  • 当前遍历是第一个,first布尔属性
  • 当前遍历是最后一个,last布尔属性
<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>

若不指定状态变量,Thymeleaf会默认生成一个名为“变量名Stat”的状态变量:

<tr th:each="prod : ${prods}" th:class="${prodStat.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>

 

七、条件运算

复制代码
<tr th:each="prod : ${prods}" th:class="${prodStat.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>  <td>    <span th:text="${#lists.size(prod.comments)}">2</span> comment/s    <a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>  </td></tr>
复制代码
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>

th:if 不只运算布尔条件,它对以下情况也运算为true:

·值不为null
  值为boolean且为true
  值为数字且非0
  值为字符且非0
  值是字符串且不是:“false”,“off”,“no”
  值不是boolean、数字、字符、字符串
·如果值为null,则th:if运算结果为false

th:if的反面是th:unless

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

th:switch 和 th:case

复制代码
<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>
复制代码

thymeleaf 学习笔记
thymeleaf,我个人认为是个比较好的模板,性能也比一般的,比如freemaker的要高,而且把将美工和程序员能够结合起来,美工能够在浏览器中查看静态效果,程序员可以在应用服务器查看带数据的效果。

thymeleaf是一个支持html原型的自然引擎,它在html标签增加额外的属性来达到模板+数据的展示方式,由于浏览器解释html时,忽略未定义的标签属性,因此thymeleaf的模板可以静态运行。

由于thymeleaf在内存缓存解析后的模板,解析后的模板是基于tree的dom节点树,因此thymeleaf适用于一般的web页面,不适合基于数据的xml。

thymeleaf 的context,即提供数据的地方,基于web的context,即WebContext相对context增加 param,session,application变量,并且自动将request atttributes添加到context variable map,可以在模板直接访问。

在模板处理前,thymeleaf还会增加一个变量execInfo,比如${execInfo.templateName},${execInfo.now}等。

数据访问模式:
${...},变量引用模式,比如${myBean.property},如果用springDialect,则使用的是spring EL,如果不用spring,则用的ognl。
*{...},选择表达式,一般是th:object之后,直接取object中的属性。当没有选取对象时,其功能等同${...},*{firstName}也等同于${#object.firstName},#object代表当前选择的对象。
@{...}链接url的表达式。th:href="@{/xxx/aa.do(id=${o.id})",会自动进行url-encoding的处理。@{...}内部可以是需要计算的表达式,比如:
th:href=”@{'/details/'+${user.login}(orderId=${o.id})}"

#{...},i18n,国际化。
需要注意的:
#{${welcomeMsgKey}(${session.user.name})}:i18n message支持占位。各个表达式支持嵌套。

表达式基本对象:
#ctx:context object
#root或者#vars
#locale
#httpServletRequest
#httpSession

表达式功能对象:
#dates:java.util.Date的功能方法类。
#calendars:类似#dates,面向java.util.Calendar
#numbers:格式化数字的功能方法类。
#strings:字符串对象的功能类,contains,startWiths,prepending/appending等等。
#objects:对objects的功能类操作。
#bools:对布尔值求值的功能方法。
#arrays:对数组的功能类方法。
#lists:对lists功能类方法
#sets
#maps
#aggregates:对数组或者集合创建聚合的功能方法,
th:text="${#aggregates.sum(o.orderLines.{purchasePrice * amount})}"

#messages:在变量表达式中获取外部信息的功能类方法。
#ids:处理可能重复的id属性的功能类方法。


条件操作:
(if)?(then):满足条件,执行then。
(if)?(then):(else)
(value)?:(defalutValue)


一些标签:
th:text="${data}",将data的值替换该属性所在标签的body。字符常量要用引号,比如th:text="'hello world'",th:text="2011+3",th:text="'my name is '+${user.name}"
th:utext,和th:text的区别是"unescaped text"。
th:with,定义变量,th:with="isEven=${prodStat.count}%2==0",定义多个变量可以用逗号分隔。
th:attr,设置标签属性,多个属性可以用逗号分隔,比如th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。
th:[tagAttr],设置标签的各个属性,比如th:value,th:action等。
可以一次设置两个属性,比如:th:alt-title="#{logo}"
对属性增加前缀和后缀,用th:attrappend,th:attrprepend,比如:th:attrappend="class=${' '+cssStyle}"
对于属性是有些特定值的,比如checked属性,thymeleaf都采用bool值,比如th:checked=${user.isActive}
th:each, 循环,<tr th:each="user,userStat:${users}">,userStat是状态变量,有 index,count,size,current,even,odd,first,last等属性,如果没有显示设置状态变量,thymeleaf会默 认给个“变量名+Stat"的状态变量。
th:if or th:unless,条件判断,支持布尔值,数字(非零为true),字符,字符串等。
th:switch,th:case,选择语句。 th:case="*"表示default case。
th:fragment,th:include,th:substituteby:fragment为片段标记,指定一个模板内一部分代码为一个片段,然后在其它的页面中用th:include或th:substituteby进行包含。
包含的格式为,格式内可以为表达式,比如th:include="footer::$(user.logined)?'logined':'notLogin'":
"templatename::fragname",指定模板内的指定片段。
"templateName::[domselector]",指定模板的dom selector,被包含的模板内不需要th:fragment.
”templatename",包含整个模板。
th:include和th:substituteby的区别在于前者包含片段的内容到当前标签内,后者是用整个片段(内容和上一层)替换当前标签(不仅仅是标签内容)。
th:remove="all|body|tag|all-but-first",一般用于将mock数据在真实环境中移除,all表示移除标签以及标签内容,body只移除内容,tag只移除所属标签,不移除内容,all-but-first,除第一条外其它不移除。


由 于一个标签内可以包含多个th:x属性,其先后顺序为:include,each,if/unless/switch/case,with,attr /attrprepend/attrappend,value/href,src ,etc,text/utext,fragment,remove。

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

内联js:
<scriptth:inline="javascript">
/*<![CDATA[*/
...
var username = /*[[${sesion.user.name}]]*/ 'Sebastian';
...
/*]]>*/
</script>

js附加代码:
/*[+
var msg = 'This is a working application';
+]*/

js移除代码:
/*[- */
var msg = 'This is a non-working template';
/* -]*/
模板缓存:
1、指定特定的缓存:
templateResolver.setCacheable(false);
templateResolver.getCacheablePatternSpec().addPattern("/users/*");
2、清除缓存:
templateEngine.clearTemplateCache();
templateEngine.clearTemplateCacheFor("/users/userList");




补充点url知识:
1、绝对路径:http://news.sina.com.cn
2、相对路径:
    2.1:页面相对路径,一般指相对当前请求的url,比如 aa.do
    2.2:上下文相对,比如/xxx/aa.do
    2.3:服务器相对路径,比如~/other/xxx/aa.do,允许切换到相同服务器不同上下文的路径。



0 0
原创粉丝点击