thymeleaf 教程

1 怎么使用

前端html页面标签中引入如下:
<html xmlns:th="http://www.thymeleaf.org">

2 表达式

  • 简单表达式
    • 可用值表达式(后台设置): ${…}
    • 所有可用值表达式: *{…}
      比如*{name} 从可用值中查找name,如果有上下文,比如上层是object,则查object中的name属性。
  • 消息表达式: #{…}
    国际化时使用,也可以使用内置的对象,比如date格式化数据
  • 链接表达式: @{…}
    用来配合link src href使用的语法
  • 片段表达式: ~{…}
    用来引入公共部分代码片段,并进行传值操作使用的语法。
  • 文字
    • 文本:'one text', 'another text', …
    • 数字:1,2,1.2,…
    • 布尔: true, false
    • 空值:null
    • 单词: something, main, name, …
  • 文本操作
    • 链接:+
    • 替换:|The name is ${name}|
<a href="" th:href="@{|/name/${test.size()}|}">链接地址:</a>  
//渲染后的结果 
<a href="/name/3">链接地址:</a>  
  • 数学操作
    • 二元操作:+, - , * , / , %
    • 一元操作: - (负)
  • 布尔操作
    • 一元 : and, or
    • 二元 : !, not
  • 比较
    • 比较:> , < , >= , <= ( gt , lt , ge , le )
    • 等于:== , != ( eq , ne )
  • 条件
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
  • 无操作
    • 使用_来禁止转义。

3 支持的操作

  • html5的操作支持:
th:abbr  
th:accept  
th:accept-charset  
th:accesskey  
th:action  
th:align  
th:alt  
th:archive  
th:audio  
th:autocomplete  
th:axis  
th:background  
th:bgcolor  
th:border  
th:cellpadding  
th:cellspacing  
th:challenge  
th:charset  
th:cite  
th:class  
th:classid  
th:codebase  
th:codetype  
th:cols  
th:colspan  
th:compact  
th:content  
th:contenteditable  
th:contextmenu  
th:data  
th:datetime  
th:dir  
th:draggable  
th:dropzone  
th:enctype  
th:for  
th:form  
th:formaction  
th:formenctype  
th:formmethod  
th:formtarget  
th:fragment  
th:frame  
th:frameborder  
th:headers  
th:height  
th:high  
th:href  
th:hreflang  
th:hspace  
th:http-equiv  
th:icon  
th:id  
th:inline  
th:keytype  
th:kind  
th:label  
th:lang  
th:list  
th:longdesc  
th:low  
th:manifest  
th:marginheight  
th:marginwidth  
th:max  
th:maxlength  
th:media  
th:method  
th:min  
th:name  
th:onabort  
th:onafterprint  
th:onbeforeprint  
th:onbeforeunload  
th:onblur  
th:oncanplay  
th:oncanplaythrough  
th:onchange  
th:onclick  
th:oncontextmenu  
th:ondblclick  
th:ondrag  
th:ondragend  
th:ondragenter  
th:ondragleave  
th:ondragover  
th:ondragstart  
th:ondrop  
th:ondurationchange  
th:onemptied  
th:onended  
th:onerror  
th:onfocus  
th:onformchange  
th:onforminput  
th:onhashchange  
th:oninput  
th:oninvalid  
th:onkeydown  
th:onkeypress  
th:onkeyup  
th:onload  
th:onloadeddata  
th:onloadedmetadata  
th:onloadstart  
th:onmessage  
th:onmousedown  
th:onmousemove  
th:onmouseout  
th:onmouseover  
th:onmouseup  
th:onmousewheel  
th:onoffline  
th:ononline  
th:onpause  
th:onplay  
th:onplaying  
th:onpopstate  
th:onprogress  
th:onratechange  
th:onreadystatechange  
th:onredo  
th:onreset  
th:onresize  
th:onscroll  
th:onseeked  
th:onseeking  
th:onselect  
th:onshow  
th:onstalled  
th:onstorage  
th:onsubmit  
th:onsuspend  
th:ontimeupdate  
th:onundo  
th:onunload  
th:onvolumechange  
th:onwaiting  
th:optimum  
th:pattern  
th:placeholder  
th:poster  
th:preload  
th:radiogroup  
th:rel  
th:rev  
th:rows  
th:rowspan  
th:rules  
th:sandbox  
th:scheme  
th:scope  
th:scrolling  
th:size  
th:sizes  
th:span  
th:spellcheck  
th:src  
th:srclang  
th:standby  
th:start  
th:step  
th:style  
th:summary  
th:tabindex  
th:target  
th:title  
th:type  
th:usemap  
th:value  
th:valuetype  
th:vspace  
th:width  
th:wrap  
th:vspace  
th:width  
th:wrap  
th:xmlbase  
th:xmllang  
th:xmlspace  
  • 布尔类型
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  

3.1 常用th标签

关键字功能介绍案例
th:valuethymeleaf格式化时间
th:value="${#dates.format(info.date, 'yyyy-MM-dd HH:mm:ss')}"  
th:id替换id
<input th:id="'xxx' + ${collect.id}"/>  
th:text文本替换
<p th:text="${collect.description}">  
    description
</p>  
th:utext支持html的文本替换
<p th:utext="${htmlcontent}">content</p>  
th:object替换对象
<div th:object="${session.user}">  
th:value属性赋值
<input th:value = "${user.name}" />  
th:with变量赋值运算
<div th:with="isEvens = ${prodStat.count}%2 == 0"></div>  
th:style设置样式
<div th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"></div>  
th:onclick点击事件
<td th:onclick = "'getCollect()'"></td>  
th:each属性赋值
<tr th:each = "user,userStat:${users}">  
th:if判断条件
<a th:if = "${userId == collect.userId}">  
th:unless和th:if判断相反
<a th:href="@{/login} th:unless=${session.user != null}">Login</a>  
th:href链接地址
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>  
th:switch多路选择配合th:case使用
<div th:switch="${user.role}">  
th:fragmentth:switch的一个分支
<p th:case = "'admin'">User is an administrator</p>  
th:includ布局标签,替换内容到引入的文件
<head th:include="layout :: htmlhead" th:with="title='xx'"></head>  
th:replace布局标签,替换整个标签到引入的文件
<div th:replace="fragments/header :: title"></div>  
th:selectdselected选择框选中
th:selected="(${xxx.id} == ${configObj.dd})"  
th:src图片类地址引入
<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />  
th:inline定义js脚本可以使用变量
<script type="text/javascript" th:inline="javascript">  
th:action表单提交的地址
<form action="subscribe.html" th:action="@{/subscribe}">  
th:remove删除某个属性
"<tr th:remove=""all"">
1.all:删除包含标签和所有的孩子。  
2.body:不包含标记删除,但删除其所有的孩子。  
3.tag:包含标记的删除,但不删除它的孩子。  
4.all-but-first:删除所有包含标签的孩子,除了第一个。  
5.none:什么也不做。这个值是有用的动态评估。"  
th:attr设置标签属性,多个属性可以用逗号分隔
比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。

4 判断操作

thymeleaf提供了几种判断,if、switch

  • 后台数据
public class TestVo {  
    private String name;
    private  Integer Score;
    private  Integer male;
    private Date birthday;

    public TestVo(String name, Integer score, Date birthday, Integer male) {
        this.name = name;
        Score = score;
        this.male = male;
        this.birthday = birthday;
    }
@RequestMapping("/test01")
    public String thymeleaf(ModelMap map){
        List<TestVo> testVos=new ArrayList<>();
        testVos.add(new TestVo("数学",10,new Date(),1));
        testVos.add(new TestVo("数学0001",70,new Date(),2));
        testVos.add(new TestVo("数学01",100,new Date(),3));
        map.put("test",testVos);
        return "/back/import/test";
    }
  • 前端语法
  <table>
       <thead>
           <th></th>
       </thead>
       <tbody>
            <tr th:each="test:${test}">
                <!--判断成绩-->
                <td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
                <td th:if="${test.Score} ge 60 and ${test.Score} le 70">中</td>
                <td th:if="${test.Score} gt 70 and ${test.Score} le 80">良</td>
                <td th:if="${test.Score} gt 80 and ${test.Score} le 90">优</td>
                <td th:if="${test.Score} gt 90 and ${test.Score} le 100">超级优秀</td>
            </tr>
            <br>
            <tr th:each="test:${test}">
                <!--判断成绩   一般只有两种情况的时候可以使用这种方式-->
                <td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
                <!--除了这些条件之外的-->
                <td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td>
            </tr>
            <tr th:each="test:${test}">
                <td th:switch="${test.male}">
                    <span th:case="1">男</span>
                    <span th:case="2">女</span>
                    <!--其他情况-->
                    <span th:case="*">未知</span>
                </td>
            </tr>

       </tbody>
   </table>

5 模板操作

主要引入公共头部和底部相关代码使用 ,当然也可以其他地方使用

  • 底部模板代码
<!DOCTYPE html>  
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">  
 <body>
  <div th:fragment="footer">
  </div>
 </body>
</html>  
  • Springboot整合引入模块
<!--写入绝对路径即可引入 -->  
<div th:include="/back/import/footer :: footer"></div>  

6 文本和带格式文本

用来输入内容到标签内部,而不是attr中。分为th:text和th:utext两种,后者可以渲染文本中的标签。 map.put("msgutext","<b>1111</b>");
<div th:utext="${msgutext}"></div> <div th:text="${msgutext}"></div>

7 外围包裹–block

有时候需要在代码外部加层条件,但写div之类的又影响样式,此情况下你可以用下面这种方式:

    <th:block th:with="score=${test.Score}">
        <td th:if="${score} ge 60">及格啦</td>
    </th:block>

8 循环

遍历元素

 <tr th:each="test:${test}">
    <td th:text="${test.Score}"></td>
 </tr>

9 循环下标判断

 List<String> list=new ArrayList<String>();
        list.add("1s");
        list.add("2s");
        list.add("3s");
        map.put("list",list);
<th:block th:each="mylist,iterStat:${list}">  
    111
    <span th:text="${mylist}"></span>
        <th:block th:if="${iterStat.index le 1}">
            <span th:text="${mylist}"></span>
        </th:block>
</th:block>  

10 常用操作

  • 日期格式化
    <td th:text="${#dates.format(content.createDate,'yyyy-MM-dd HH:mm:ss')}"></td>
  • 字符截取长度
<td th:if="${#strings.length(content.title) gt 5 } "  
    th:text="${#strings.substring(content.title,0,5) + '…'}">
</td>  
  • 下拉选择
<select name="subId" id="subId" lay-verify="" >  
  <option value="">请选择</option>
   <option th:each="channelsub:${subchannels}" 
           th:selected="${channelsub.id == subId}"    
           th:value="${channelsub.id}" 
           th:text="${channelsub.name}">
    </option>
</select>  

11 js取值

有时候需要传递参数到js中,按如下方式:

  <script th:inline="javascript"  >
        var size= [[${test.size()}]];
        console.info(size)
    </script>
  • 进阶
    ps: 下面涉及到thymeleaf的语法出,可以替换成其他thymeleaf的语法来用
 <script th:inline="javascript"  >
        //尺寸等于3时打印日志..
        /*[# th:if="${test.size() eq 3}"]*/
        console.info('Welcome admin');
        /*[/]*/
    </script>

12 css取值

首先需要后台设置classname、align的值,之后按如下方式:

<style th:inline="css">  
  .[[${classname}]] {
      text-align: [[${align}]];
  }
</style>  

转载至 thymeleaf快速入门教程

Finn

继续阅读此作者的更多文章