thymeleaf快速入门教程

时间:2025-02-15 08:44:24

支持的操作

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

判断操作

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="${} gt 0 and ${} lt 60"></td>
                <td th:if="${} ge 60 and ${} le 70"></td>
                <td th:if="${} gt 70 and ${} le 80"></td>
                <td th:if="${} gt 80 and ${} le 90"></td>
                <td th:if="${} gt 90 and ${} le 100">超级优秀</td>
            </tr>
            <br>
            <tr th:each="test:${test}">
                <!--判断成绩   一般只有两种情况的时候可以使用这种方式-->
                <td th:if="${} gt 0 and ${} lt 60"></td>
                <!--除了这些条件之外的-->
                <td th:unless="${} gt 0 and ${} lt 60">及格</td>
            </tr>
            <tr th:each="test:${test}">
                <td th:switch="${}">
                    <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:///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

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

结果:被渲染了

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

结果:原样输出到页面。

外围包裹–block

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

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

循环

遍历元素

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

循环下标判断

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

常用操作

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

js取值

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

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

css取值

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

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

结语

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