锋利的Java模板引擎——thymeleaf
  顶级码农   10/23/22 7:57:17 AM
Thymeleaf是一个现代的服务器端Java模板引擎的web和独立的环境,能够处理HTML, XML, JavaScript, CSS,甚至纯文本。

导航

  • thymeleaf介绍
  • thymeleaf标准表达语法
  • th 常用属性
  • 在Springboot项目中集成thymeleaf
    • MVC模式
    • 在pom文件引入thymeleaf依赖
    • 配置thymeleaf
    • 编写模板文件
    • 编写controller
    • 测试
  • 结语
  • 参考


在前后端分离日渐流行的今天,很多技术文章和博客都会推荐这种架构,比如前端使用vue,后端使用springboot webapi。

在实际工作中,也确实是这样在使用。但值得注意的是,这种前后端分离的模式一般是由前端和后端两名开发人员配合才能完成。

对于初学者来说,这样的模式显然学习成本过高,令人望而却步。

thymeleaf介绍

Thymeleaf是一个Java类库。

Thymeleaf是一个现代的服务器端Java模板引擎的web和独立的环境,能够处理HTML, XML, JavaScript, CSS,甚至纯文本。

Thymeleaf的主要目标是提供一种优雅的和高度可维护的方式来创建模板。为了实现这一点,它构建在自然模板的概念上,以不影响模板作为设计原型使用的方式将其逻辑注入模板文件。这改进了设计的交流,并在设计和开发团队之间架起了桥梁。

Thymeleaf的设计之初就考虑了Web标准——尤其是HTML5——允许你创建完全验证模板。

开箱即用,Thymeleaf允许您处理六种模板,其中每一种被称为模板模式:

  • HTML
  • XML
  • TEXT
  • JAVASCRIPT
  • CSS
  • RAW

Note: 如果您有使用过ASP.NET MVCRazor引擎,那么可以进行类比理解Thymeleaf

标准表达式语法

任何一种语言,都有其语法约束,前端模板引擎也不例外。本文将介绍Thymeleaf方言中最重要的部分之一——标准表达式语法。

Thymeleaf标准表达式语法的基本内容如下:

  • 简单表达式

    • 变量表达式:${...}
    • 选择变量表达式:*{...}
    • 消息表达式:#{...}
    • 链接URL表达式:@{...}
    • 片段表达式:~{...}
  • 常量

    • 文本常量:'one text', 'Another one!',…
    • 数字常量:0, 34, 3.0, 12.3,…
    • 布尔常量:true,false
    • 空常量:null
    • 常量标记:one, sometext, main,…
  • 文字操作:

    • 字符串串联: +
    • 文字替换: |The name is ${name}|
  • 算术运算:

    • 二元运算符:+,-,*,/,%
    • 减号(一元运算符): -
  • 布尔运算:

    • 二元运算符:and,or
    • 布尔否定(一元运算符): !,not
  • 比较和相等:

    • 比较:>,<,>=,<=(gt,lt,ge,le)
    • 等号运算符:==,!=(eq,ne)
  • 条件运算符:

    • 如果-则: (if) ? (then)
    • 如果-则-否则: (if) ? (then) : (else)
    • 默认: (value) ?: (defaultvalue)
  • 特殊令牌:

    • 无操作: _

所有这些特性都可以组合和嵌套:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

这里的表达式语法比较多,在superblog项目中使用的最多的还是变量表达式。

比如,article/deail.html中

<div th:utext="${article.content}"></div>

<div layout:fragment="content" >
    <div class="page-content">
        <div class="page-content-area">
            <article class="markdown-body">
              <div th:utext="${article.content}"></div>
            </article>
        </div>
    </div>
</div>

还有header.html中

 <span class="user-info" th:if="${session.aname != null}">
      <small>欢迎您,</small>
<div th:text="${session.aname}"></div>
</span>

th 常用属性

Thymeleaf 还提供了大量的 th 属性,这些属性可以直接在 HTML 标签中使用。

th:text对应的是HTML5中的text 属性,除th:text属性外,Thymeleaf 也提供了其他的标签属性来替换 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:xmlbase th:xmllang th:xmlspace

从上面表格中可以看看出,

  • th:class 对应 HTML5 中的 class 属性
  • th:href 对应 HTML5 中的链接地址属性
  • th:id 和 th:name 分别对应 HTML5 中的 id 和 name 属性...

本文剩余精彩内容,欢迎 登录查看!

进入登录