The basic usage Thymeleaf

The basic usage Thymeleaf

It is a personal document finishing, the source of most of the content from the network

Here we do not intend to use to integrate SpringMVC use or used in conjunction with Spring Boot

We use Servelet version alone here - in order to be regarded as part of the code of some beginners

Thymeleaf is a tool for rendering XML / XHTML / HTML5 content template engine, similar to JSP, Velocity, FreeMaker etc. It can also be easily integrated template engine as a Web application and Web frameworks such as Spring MVC.

Thymeleaf biggest feature is the ability to open directly in the browser and displays the correct page template without the need to start the entire Web application, but always see that its a bit low

Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

1. The introduction of prompt

Introducing thymeleaf namespace html page, that is, by the dynamic properties using th in the html template file: namespace-qualified.
<html lang="en" xmlns:th="http://www.thymeleaf.org">

So that it can be used in other tags inside th: * This is the syntax following syntax. Premise .

2. Variable expression (fetch values)

<div th:text="'你是否读过,'+${session.book}+'!!'">
    同EL表达式有些相似的效果,如果有数据,被替换
    完成前后端分离效果(美工代码)
</div>
代码分析:
1.可以看出获取变量值用$符号,对于javaBean的话使用变量名.属性名方式获取,这点和EL表达式一样
2.它通过标签中的th:text属性来填充该标签的一段内容,意思是$表达式只能写在th标签内部,不然不会生效,上面例子就是使用th:text标签的值替换div标签里面的值,至于div里面的原有的值只是为了给前端开发时做展示用的.这样的话很好的做到了前后端分离.意味着div标签中的内容会被表达式${session.book}的值所替代,无论模板中它的内容是什么,之所以在模板中“多此一举“地填充它的内容,完全是为了它能够作为原型在浏览器中直接显示出来。
3.访问spring-mvc中model的属性,语法格式为“${}”,如${user.id}可以获取model里的user对象的id属性 
4.牛叉的循环<li th:each="book : ${books}" >

3.URL expression (introduced URL)

Focus! Focus! Focus!

  • Reference a static resource files (CSS using th: href, js that use th: src)

  • href link URL (use th: href)

    代码分析
    1.最终解析的href为:    
        /seconddemo/    
        /seconddemo/usethymeleaf?name=Dear 相对路径,带一个参数   
        /seconddemo/usethymeleaf?name=Dear&alis=Dear 相对路径,带多个参数
        /seconddemo/usethymeleaf?name=Dear&alis=Dear 相对路径,带多个参数
        /seconddemo/usethymeleaf/Dear 相对路径,替换URL一个变量
        /seconddemo/usethymeleaf/Dear/Dear 相对路径,替换URL多个变量
    2.URL最后的(name=${name})表示将括号内的内容作为URL参数处理,该语法避免使用字符串拼接,大大提高了可读性
    3.@{/usethymeleaf}是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为seconddemo,那么结果应该是/seconddemo/usethymeleaf,即URL中以”/“开头的路径(比如/usethymeleaf将会加上服务器地址和域名和应用cotextpath,形成完整的URL。
    4.th:href属性修饰符:它将计算并替换使用href链接URL 值,并放入的href属性中。
    5.th:href中可以直接使用静态地址
    

4. Select an expression or an asterisk

Expressions like variable expression, but they use a pre-selected target instead of a context variable container (Map) is performed*{customer.name}

<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>
1.如果不考虑上下文的情况下,两者没有区别;星号语法评估在选定对象上表达,而不是整个上下文,什么是选定对象?就是父标签的值。上面的*{title}表达式可以理解为${book.title}。(父对象)  
2.当然,美元符号和星号语法可以混合使用
Episode: variable expression of three and four, URL expression corresponding attributes can be used in a uniform manner: th.attr = "attribute name = attribute value" way to set the reference section. "Seven set property values." section

The international character of expression

j can simply look at the text of an international expression allows us to get a text message area (.properties) from an external file, use Key Index Value, can also provide a set of parameters (optional).

#{main.title}    
#{message.entrycreated(${entryId})} 可以在模板文件中找到这样的表达式代码:    
<table>
    <th th:text="#{header.address.city}"> <th th:text="#{header.address.country}"> </table>

6. The expression syntax support

  • Literal (Literals)

    • Text Text (Text literals): 'one text', 'Another one!', ...
    • Digital Text (Number literals): 0, 34, 3.0, 12.3, ...
    • Boolean text (Boolean literals): true, false
    • 空(Null literal): null
    • Word mark (Literal tokens): one, sometext
  • Operation text (Text operations)

    • String concatenation (String concatenation): +
    • Replace Text (Literal substitutions): |The name is ${name}|

      <div th:class="'content'">...</div> <span th:text="|Welcome to our application, ${user.name}!|"> //Which is equivalent to: <span th:text="'Welcome to our application, ' + ${user.name} + '!'"> <span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|">
  • Arithmetic (Arithmetic operations)

    • Binary operator (Binary operators): +, -, *, /,%
    • MINUS (Minus sign (unary operator)): -
  • Boolean operations (Boolean operations)

    • Binary operators: and , or
    • Boolean negation (unary operator): ! , not
  • Comparison and equivalents (Comparisons and equality)

    • Comparators: > , < , >= , <= ( gt , lt , ge , le )
    • Equality operators: == , != ( eq , ne )
  • Conditional operator (Conditional operators) ternary operator

    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
    示例一:    
    <h2 th:text="${expression} ? 'Hello' : 'Something else'"></h2> 示例二:        <!-- IF CUSTOMER IS ANONYMOUS -->     <div th:if="${customer.anonymous}">         <div>Welcome, Gues!</div>     </div>     <!-- ELSE -->     <div th:unless="${customer.anonymous}">         <div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>     </div>
  • Special tokens:

    • No-Operation: _
  • switch

  • cycle

    Rendering a list of data is a very common scenario, for example, there are n records need to be rendered into a table or a list of label li the data set must be traversed, the use of th:eachlabels

    代码分析:
    循环,在html的标签中,加入th:each=“value:${list}”形式的属性,如可以迭代prods的数据 又如带状态变量的循环:

Using the state variables determined:

7. Set the attribute value

1. th:attr 
    任何属性值,语法格式:th:attr="属性名=属性值,[属性名=属性值]" 
    属性值如果是使用表达式的话:通常有URL表达式@{}和变量表达式${}        
    但此标签语法不太优雅    
    示例:        
th:attr="action=@{/subscribe}" //当然也可以直接使用th:action                    
th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" //可直接使用th:src  
th:attr="value=#{subscribe.submit}"//可直接使用th:value        
<input type="checkbox" name="active" th:attr="checked=${user.active}"/>         设置多个属性在同一时间,有两个特殊的属性可以这样设置:  th:alt-title 和 th:lang-xmllang         th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}"      2.前置和后置添加属性值   th:attrappend 和 th:attrprepend        主要对class和style两个属性         class="btn" th:attrappend="class=${' ' + cssStyle}"        转换后:class="btn warning"      3.还有两个特定的添加属性  th:classappend 和 th:styleappend        与上面的attrappend功能一样         class="row" th:classappend="${prodStat.odd}? 'odd'"          转换后:奇数行class="row odd",偶数行class="row" 

8. embedded variable Utilities

为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问。

dates : java.util.Date的功能方法类    
calendars : 类似#dates,面向java.util.Calendar    
numbers : 格式化数字的功能方法类     strings : 字符串对象的功能类,contains,startWiths,prepending/appending等等     objects: 对objects的功能类操作     bools: 对布尔值求值的功能方法     arrays:对数组的功能类方法     lists: 对lists功能类方法     sets     maps
代码示例:    
${#dates.format(dateVar, 'dd/MMM/yyyy HH:mm')}    
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}    
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}    
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}    
${#dates.createNow()}    
${#dates.createToday()}    
${#strings.isEmpty(name)}    
${#strings.arrayIsEmpty(nameArr)}    
${#strings.listIsEmpty(nameList)}    
${#strings.setIsEmpty(nameSet)}    
${#strings.startsWith(name,'Don')}                  
// also array*, list* and set*    
${#strings.endsWith(name,endingFragment)}           
// also array*, list* and set*    
${#strings.length(str)}     
${#strings.equals(str)}    
${#strings.equalsIgnoreCase(str)}    
${#strings.concat(str)}    
${#strings.concatReplaceNulls(str)}    
${#strings.randomAlphanumeric(count)}//产生随机字符串

9.thymeleaf布局

10.附录

参照:https://segmentfault.com/a/1190000017563310#articleHeader6

Guess you like

Origin www.cnblogs.com/zxrxzw/p/11123433.html