冲刺第二天——Thymeleaf

电子公文传输系统团队冲刺第二天

——Thymeleaf

 

一、Thymeleaf

  1、用途

  Thymeleaf是一个现代服务器端 Java 模板引擎,用于 Web 和独立环境。

  Thymeleaf 的主要目标是将优雅的自然模板引入开发工作流 —— HTML,它可以在浏览器中正确显示,也可以作为静态原型工作,从而在开发团队中实现更强的协作。

  2、feature

  ①Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

     ②Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
     ③Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

 

 

二、基本用法总结

 1、引用命名空间 <html xmlns:th="http://www.thymeleaf.org"> 

        在html中引入此命名空间,可避免编辑器出现html验证错误,虽然加不加命名空间对Thymeleaf的功能没有任何影响。

 

 2、输出内容

        2.1  <p th:text="#{home.welcome}">Welcome to our grocery store!</p>

        说明:

                 1. th:text  用来将内容输出到所在标签的body中。

                 2. #{home.welcome} 用来引入数据home对象中的 welcome属性。

                 3. 可以用th:utext 用来显示“unescaped ” 的html内容。

        2.2    <p>Today is: <span th:text="${today}">13 February 2011</span></p>

        说明:${today} 用来引用 today 变量

 

 3、访问对象      

       ${param.x} 返回名为x 的 request参数。(可能有多个值)

       ${session.x} 返回名为x的Session参数。

       ${application.x} 返回名为 servlet context 的参数。

     

 4、基本语法

       4.1  #{home.welcome} --  访问数据

       4.2  #{home.welcome(${session.user.name})}  -- 格式化数据 当 home.welcome 为 "abcdegf{0}"  类似这种内容时。(多个参数以逗句分隔)。

       4.3  ${today} --- 访问变量

       4.4  访问基本对象

#ctx: the context object.
#vars: the context variables.
#locale: the context locale.
#request: (only in Web Contexts) the HttpServletRequest object.
#response: (only in Web Contexts) the HttpServletResponse object.
#session: (only in Web Contexts) the HttpSession object.
#servletContext: (only in Web Contexts) the ServletContext object.

 

        4.5  日期的输出

<span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span>

 

        4.6  星号语法

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

 

  4.7  输出URL

<a href="product/list.html" th:href="@{/product/list}">Product List</a>

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

 

       4.8  使用代码段

<div th:insert="~{commons :: main}">...</div>

 

       4.9  直接输出内容   

<span th:text="'working web application'"> -- 输出字符

<span th:text="2013 + 2">  -- 输出数据表达式

<div th:if="${user.isAdmin()} == false">  --输出布尔表达式

<span th:text="'Welcome to our application, ' + ${user.name} + '!'"> -- 带变量的

 

        4.10 条件表达式

<tr th:class="${row.even}? 'even' : 'odd'">
...  
</tr>
<tr th:class="${row.even}? 'alt'">
...省略 false 结果的表达方式
</tr>

<div th:object="${session.user}">
...省略 true 结果的表达方式
<p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
</div>

<span th:text="${user.name} ?: _">no user authenticated</span> --不做任何处理时用下划线 _ 表示

 

      4.11  格式化 

<td th:text="${{user.lastAccessDate}}">...</td> --${{.}}  调用默认的格式化器来输出结果。

 

       4.12  预处理

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

       说明:thymeleaf 的处理模板内容的顺序与书写顺序无关,只能通过  __${expression}__ ,来将需要先一步计算出来后面          要用的变量指定为优化处理。

 

  5、设置 Attribute 值

       5.1 设置任何Attribute 的方法

       <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>   --设置单个

       <img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />  --一次设置多个

        5.2 设置一些内置的Attribute的方法   

 <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>

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

       <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>

       <img src="../../images/gtvglogo.png"  th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" /> -- 一次设置多个(alt title)的方法

 

        5.3 设置html里没有指的任何属性的语法

<span th:whatever="${user.name}">...</span>   ---whatever 可以换成任何你想设的属性

 

 

 6、循环输出的语法

       6.1 基本循环

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

 

  6.2 循环状态的使用

<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、条件判断

       7.1 if 和 unless

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

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

 

       7.2 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>
<p th:case="*">User is some other thing</p>    --默认的 case 相当于default
</div>

 

 8、模板 include

      8.1 定义和引用代码块

定义代码块

<!DOCTYPE html>

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

<body>

<div th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</div>

</body>

</html>

引用代码块

<body>

...

<div th:insert="~{footer :: copy}"></div>

</body>

引用未用fragment 标注的代码块 

<div id="copy-section">
&copy; 2011 The Good Thymes Virtual Grocery
</div>

<body>

...

<div th:insert="~{footer :: #copy-section}"></div>

</body>

 

  8.2 th:insert th:replace th:include 之间的区别

  th:insert  --- 插入代码块    th:replace -- 替换代码块会替换掉容器标签。

  th:include ---- 和insert相似但只会插入fragment标注body内的内容。

 

  8.3  带参数的代码段

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

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

 

 9、局部变量的使用示例

<div th:with="firstPer=${persons[0]}">
<p>
The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
</p>
</div>

<div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
<p>
The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
</p>
<p>
But the name of the second person is
<span th:text="${secondPer.name}">Marcus Antonius</span>.
</p>
</div>

 

 10、注释

        <!-- ... -->  

 

三、标准表达式语法

${...} 变量表达式,Variable Expressions

@{...} 链接表达式,Link URL Expressions

#{...} 消息表达式,Message Expressions

~{...} 代码块表达式,Fragment Expressions

*{...} 选择变量表达式,Selection Variable Expressions

~{...} 代码块表达式

支持两种语法结构

推荐:~{templatename::fragmentname}

支持:~{templatename::#id}

templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。

fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment="fragmentname"

id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。

代码块表达式的使用

代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。

th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,

th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,

th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中,

#{...} 消息表达式

消息表达式一般用于国际化的场景。

@{...} 链接表达式

链接表达式好处

不管是静态资源的引用,form表单的请求,凡是链接都可以用@{...} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问

链接表达式结构

无参:@{/xxx}

有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2

引入本地资源:@{/项目本地的资源路径}

引入外部资源:@{/webjars/资源在jar包中的路径}

${...} 变量表达式

变量表达式功能

一、可以获取对象的属性和方法

二、可以使用ctx,vars,locale,request,response,session,servletContext内置对象

三、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法(重点介绍)

              常用的内置对象

一、ctx :上下文对象。

二、vars :上下文变量。

三、locale:上下文的语言环境。

四、request:(仅在web上下文)的 HttpServletRequest 对象。

五、response:(仅在web上下文)的 HttpServletResponse 对象。

六、session:(仅在web上下文)的 HttpSession 对象。

七、servletContext:(仅在web上下文)的 ServletContext 对象

              常用的内置方法

一、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等

二、numbers:数值格式化方法,常用的方法有:formatDecimal等

三、bools:布尔方法,常用的方法有:isTrue,isFalse等

四、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等

五、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等

六、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等

七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等

 

posted @ 2020-11-29 17:55  BBBBLUE  阅读(159)  评论(0编辑  收藏  举报