thymeleaf快速入门教程

来源:互联网 发布:淘宝会员号是什么 编辑:程序博客网 时间:2024/06/03 23:48

thymeleaf教程

本教程涵盖了常见的前端操作,比如,判断,循环,引入模板,常用函数(日期格式化,字符串操作)下拉,js和css中使用,基本可以应对一般场景。

怎么使用?

前端html页面标签中引入如下:

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

表达式

  • 简单表达式

    • 可用值表达式(后台设置): ${…}
    • 所有可用值表达式: *{…}

    比如*{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}|
      html
      <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)
  • 无操作
    使用_ 来禁止转义。

  • 支持的操作

    html5的操作支持:

    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:classidth:codebase             th:codetype             th:colsth:colspan             th:compact             th:contentth:contenteditable             th:contextmenu             th:datath:datetime             th:dir             th:draggableth:dropzone             th:enctype             th:forth:form             th:formaction             th:formenctypeth:formmethod             th:formtarget             th:fragmentth:frame             th:frameborder             th:headersth:height             th:high             th:hrefth:hreflang             th:hspace             th:http-equivth:icon             th:id             th:inlineth:keytype             th:kind             th:labelth:lang             th:list             th:longdescth:low             th:manifest             th:marginheightth:marginwidth             th:max             th:maxlengthth:media             th:method             th:minth:name            th:onabort            th:onafterprintth:onbeforeprint            th:onbeforeunload            th:onblurth:oncanplay            th:oncanplaythrough            th:onchangeth:onclick            th:oncontextmenu            th:ondblclickth:ondrag            th:ondragend            th:ondragenterth:ondragleave            th:ondragover            th:ondragstartth:ondrop            th:ondurationchange            th:onemptiedth:onended            th:onerror            th:onfocusth:onformchange            th:onforminput            th:onhashchangeth:oninput            th:oninvalid            th:onkeydownth:onkeypress            th:onkeyup            th:onloadth:onloadeddata            th:onloadedmetadata            th:onloadstartth:onmessage            th:onmousedown            th:onmousemoveth:onmouseout            th:onmouseover            th:onmouseupth:onmousewheel            th:onoffline            th:ononlineth:onpause            th:onplay            th:onplayingth:onpopstate            th:onprogress            th:onratechangeth:onreadystatechange            th:onredo            th:onresetth:onresize            th:onscroll            th:onseekedth:onseeking            th:onselect            th:onshowth:onstalled            th:onstorage            th:onsubmitth:onsuspend            th:ontimeupdate            th:onundoth:onunload            th:onvolumechange            th:onwaitingth:optimum            th:pattern            th:placeholderth:poster            th:preload            th:radiogroupth:rel            th:rev            th:rowsth:rowspan            th:rules            th:sandboxth:scheme            th:scope            th:scrollingth:size            th:sizes            th:spanth:spellcheck            th:src            th:srclangth:standby            th:start            th:stepth:style            th:summary            th:tabindexth:target            th:title            th:typeth:usemap            th:value            th:valuetypeth:vspace            th:width            th:wrapth:vspace            th:width            th:wrapth:xmlbase            th:xmllang            th:xmlspace

    布尔类型

    th:async th:autofocus th:autoplayth:checked th:controls th:declareth:default th:defer th:disabledth:formnovalidate th:hidden th:ismapth:loop th:multiple th:novalidateth:nowrap th:open th:pubdateth:readonly th:required th:reversedth:scoped th:seamless th:selected

    判断操作

    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>
    • 结果



    超级优秀


    及格
    及格


    模板操作

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

    底部模板代码

    <!DOCTYPE html><html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"><body><div th:fragment="footer">    © 2016 xxx</div></body></html>

    Springboot整合引入模块

    <!--写入绝对路径即可引入 --><div th:include="/back/import/footer :: footer"></div>

    文本和带格式文本

    用来输入内容到标签内部,而不是attr中。分为th:text和th:utext两种,后者可以渲染文本中的标签。
    - th:utext

        map.put("msgutext","<b>1111</b>");
    <div th:utext="${msgutext}"></div>

    结果:被渲染了

    • th:text
    <div th:text="${msgutext}"></div>

    结果:原样输出到页面。

    外围包裹–block

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

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

    循环

    遍历元素

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

    循环下标判断

     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>

    常用操作

    • 日期格式化
     <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>

    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>

    css取值

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

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

    结语

    thymeleaf还有很多其他的语法,这里只是做个入门,方便上手,详细教程请参阅 官方教程。当然也可以加群交流。