Thymeleaf

Thymeleaf 简介

Thymeleaf是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。
相较与其他的模板引擎,它有如下三个极吸引人的特点:
1. Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
2. Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
3. Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

应用

1)只需加入最新jar,目前是thymeleaf-3.0.1.RELEASE.jar包,
http://www.thymeleaf.org/download.html

若用maven,则加入如下配置

<dependency>    
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>           
  <version>3.0.1</version>
</dependency>

若用spring boot,则加入如下配置

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

2)增加头文件。

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

3)用th标签动态替换掉静态数据。

如下图,后台传出的message会将静态数据“Red Chair”替换掉,若访问静态页面,则显示数据“Red Chair”

<td th:text="${message}">Red Chair</td>

th标签整理
变量表达式 ${……}
引用user对象的name属性值,

<input type="text" name="userName" value="James Carrot" th:value="${user.name}" />

选择/星号表达式 *{……}
选择表达式一般跟在th:object后,直接取object中的属性,

<div th:object="${session.user}">                                                                                            
    <p>
      Nationality: 
      <span th:text="*{nationality}">Saturn</span>.
    </p>    
</div>

文字国际化表达式 #{……}
调用国际化的welcome语句,国际化资源文件如下
resource_en_US.properties:

home.welcome=Welcome to here!

resource_zh_CN.properties:

home.welcome=欢迎您的到来!
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>

URL表达式 @{……}
@{……}支持决定路径和相对路径。其中相对路径又支持跨上下文调用url和协议的引用

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

当URL为后台传出的参数时,代码如下

<img src="../../static/assets/images/qr-code.jpg" th:src="@{${path}}" alt="二维码" />

简单数据转换(数字,日期)

<dt>价格</dt>
<dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">180</dd>
<dt>进货日期</dt>
<dd th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</dd>

字符串拼接

<dd th:text="${'$'+product.price}">235</dd>

转义和非转义文本
当后台传出的数据为“This is an <em>HTML</em> text. <b>Enjoy yourself!</b>”时,若页面代码如下则出现两种不同的结果

<div th:text="${html}">
  This is an &lt;em&gt;HTML&lt;/em&gt; text. &lt;b&gt;Enjoy yourself!&lt;/b&gt;
</div> 
<div th:utext="${html}">
  This is an <em>HTML</em> text. <b>Enjoy yourself!</b>
</div>

表单

<form th:action="@{/bb}" th:object="${user}" method="post" th:method="post">    
  <input type="text" th:field="*{name}"/>    
  <input type="text" th:field="*{msg}"/>    
  <input type="submit"/>
</form>

显示页面的数据迭代
用 th:remove 移除除了第一个外的静态数据,用第一个tr标签进行循环迭代显示
将后台传出的 productList 的集合进行迭代,用product参数接收,通过product访问属性值
用count进行统计,有顺序的显示

<tbody th:remove="all-but-first">   
<tr th:each="product:${productList}">
<td th:text="${productStat.count}">1</td>  
<td th:text="${product.description}">Red Chair</td>
<td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$123</td>                 
</tr>        
<tr>            
<td>White table</td>                
<td>$200</td>                
<td>15-Jul-2013</td>        
</tr>        
<tr>            
<td>Reb table</td>                
<td>$200</td>                
<td>15-Jul-2013</td>        
</tr>        
<tr>            
<td>Blue table</td>                
<td>$200</td>                
<td>15-Jul-2013</td>
</tr>
</tbody>

条件判断
不能用”<”,”>”等符号,要用”lt”等替代

例如:
当gender存在时,选择对应的选项;若gender不存在或为null时,取得customer对象的name

<span th:if="${product.price lt 100}" class="offer">Special offer!</span>
<td th:switch="${customer.gender?.name()}">    
<img th:case="'MALE'" src="../../../images/male.png" th:src="@{/images/male.png}" alt="Male" />    
<img th:case="'FEMALE'" src="../../../images/female.png" th:src="@{/images/female.png}" alt="Female" />    
<span th:case="*">Unknown</span></td>

根据后台数据选中select的选项

<div class="form-group col-lg-6">      
 <label >性别<span>&nbsp;Sex:</span></label>      
 <select th:field="${resume.gender}" class="form-control"  th:switch="${resumes.gender.toString()}" 
data-required="true">              
  <option value="男" th:case="'男'" th:selected="selected" ></option>              
  <option value="女" th:case="'女'" th:selected="selected" ></option>              
  <option value="">请选择</option>      
 </select> 
</div>

表达式基本对象
在上下文变量评估OGNL表达式时,一些对象表达式可获得更高的灵活性。这些对象将由#号开始引用。
- #ctx: 上下文对象.
- #vars: 上下文变量.
- #locale: 上下文语言环境.
- #httpServletRequest: (仅在web上文)HttpServletRequest 对象.
- #httpSession: (仅在web上文) HttpSession 对象.

表达式功能对象
- #dates:java.util.Date对象的实用方法。
- #calendars:和dates类似, 但是 java.util.Calendar 对象.
- #numbers: 格式化数字对象的实用方法。
- #strings: 字符创对象的实用方法: contains, startsWith, prepending/appending等.
- #objects: 对objects操作的实用方法。
- #bools: 对布尔值求值的实用方法。
- #arrays: 数组的实用方法。
- #lists: list的实用方法。
- #sets: set的实用方法。
- #maps: map的实用方法。
- #aggregates: 对数组或集合创建聚合的实用方法。
- #messages: 在表达式中获取外部信息的实用方法。
- #ids: 处理可能重复的id属性的实用方法 (比如:迭代的结果)。

给特定的属性设值
–th:action:给action设值。

<form action="subscribe.html" th:action="@{/subscribe}">

还有很多这样的属性,它们每一个都针对一个特定的XHTML或者HTML5属性:

–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: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。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值