学习笔记-Thymeleaf

20 篇文章 0 订阅

学习笔记-Thymeleaf

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_40693171/article/details/107008457

​ 注意,本文章的thymeleaf均为配合springboot集成使用。

1. 介绍

​ 本部分先介绍thymeleaf的本质——模板引擎,再对thymeleaf本身进行相关介绍。

1.1 模板引擎 (templates)

  • 简介:

    ​ (此处特指用于Web开发的模板引擎)为了使用户界面与业务数据(内容)分离而产生。它可以生成特定格式的文档,例如用于网站的模板引擎就会生成一个标准的html文档。

    ​ Java中的模板引擎有很多,模板引擎是动态网页发展进步的产物,在最初并且流传度最广的 jsp 就是一个模板引擎。jsp是官方标准的模板,但是由于jsp的缺点较多,很多人弃用jsp选用第三方的模板引擎,市面上开源的第三方的模板引擎有很多,例如 ThymeleafFreeMakerVelocity 等。

  • 作用:

    ​ 从字面上理解模板引擎,做好一个模板后套入对应位置的数据,最终以html的格式展示出来。让网站实现界面和数据分离,这样大大提高了开发效率,让代码重用更加容易。

1.2 thymeleaf

  • 官方介绍:

    “Thymeleaf is a modern server-side Java template engine for both web and standalone environments.”

  • 简介:

    ​ Thymeleaf是适用于Web和独立环境的现代服务器端 Java 模板引擎。Thymeleaf的主要目标是为您的开发工作流程带来优雅自然的模板-HTML可以在浏览器中正确显示,也可以作为静态原型工作,从而可以在开发团队中加强协作。

  • 优势:

    Spring官方支持的服务的渲染模板中,并不包含jsp,而是Thymeleaf和Freemarker等。Thymeleaf拥有适用于Spring Framework的模块,与您喜欢的工具的大量集成以及插入您自己的功能的能力,对于现代HTML5 JVM Web开发而言,Thymeleaf是理想的选择。Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,我们只用关注Thymeleaf的语法即可。

  • 特点:

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

2. 语法详解

​ 本部分对thymeleaf的语法进行相关介绍。

2.1 配置

​ Springboot官方对Thymeleaf做了很多默认配置,而我们在引入Thymeleaf的jar包依赖后可以根据自己特定需求进行更细化的配置,例如页面缓存、字体格式设置等等。

​ Springboot官方提供的配置内容有以下:

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.cache=true # Whether to enable template caching.
spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.chunked-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
spring.thymeleaf.reactive.full-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
spring.thymeleaf.reactive.max-chunk-size=0 # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names (patterns allowed) that can be resolved.

​ 上面的配置有些我们可能不常使用,因为Springboot官方做了默认配置大部分能够满足我们的使用需求,但如果项目有特殊需求可以妥善使用这些配置。常用的修改如下:

  • spring.thymeleaf.cache = false: 是否允许页面缓存的配置,我们在开发时候要确保页面是最新的所以需要禁用缓存;而在上线运营时可能页面不常改动为了减少服务端压力以及提升客户端响应速度会允许页面缓存的使用。
  • spring.thymeleaf.encoding=UTF-8:确定页面的编码,但如果你的项目是GBK编码就需要将它改成GBK。
  • spring.thymeleaf.prefix=classpath:/templates/:Springboot默认模板引擎文件是放在templates目录下。如果有需求可修改配置,将templates改为自己需要的目录。同理其他的配置如果需要自定义化也可参照上面配置进行修改。

​ 此外,我们需要加入特定标签来声明和使用Thymeleaf的语法,即在Thymeleaf的头部加Thymeleaf标识

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

2.2 常用标签

​ Thymeleaf通过特殊的标签来寻找属于Thymeleaf的部分,替换对应位置内容,并渲染该部分内容。Thymeleaf标签有很多很多,功能也很丰富,这里列举一些比较常用的标签如下:

标签作用举例
th:idid替换<input th:id="${user.id}"/>
th:text文本替换<p text:="${user.name}">bigsai</p>
th:utext支持html的文本替换<p utext:="${htmlcontent}">content</p>
th:object对象替换<div th:object="${user}"></div>
th:value值替换<input th:value="${user.name}" >
th:each迭代<tr th:each="student:${user}" >
th:href超链接替换<a th:href="@{index.html}">超链接</a>
th:src资源替换<script type="text/javascript" th:src="@{index.js}"></script>

2.3 链接表达式 @{…}

​ 在Thymeleaf 中,如果想引入链接比如link,href,src,需要使用@{src}引入资源。其中资源地址可以为static目录下的静态资源,也可以是互联网中的绝对资源。

  • CSS

     <link rel="stylesheet" th:href="@{index.css}">
    
  • Javascript

     <script type="text/javascript" th:src="@{index.js}"></script>
    
  • href

    <a th:href="@{index.html}">href</a>
    

2.4 变量表达式 ${…}

​ 在Thymeleaf中可以通过${…}进行取值,这点和ONGL表达式语法一致。

  • 普通字符串

    ​ 如果在controller中的Model直接存储某字符串,我们可以直接${对象名}进行取值。示例代码如下:

    <h2>String</h2>
    <table border="0">
        <tr>
            <td th:text="'My name is:' + ${name}"></td>
        </tr>
    </table>
    
  • JavaBean对象

    ​ 由于JavaBean自身有一些其他属性,所以咱们就可以使用${对象名.对象属性}或者${对象名['对象属性']}来取值。除此之外,如果该JavaBean如果写了get方法,也可以通过它取值,如${对象.get方法名}。示例代码如下:

    <h2>JavaBean Object</h2>
    <table bgcolor="#ffe4c4" border="1">
        <tr>
            <td>介绍</td>
            <td th:text="${user.name}"></td>
        </tr>
        <tr>
            <td>年龄</td>
            <td th:text="${user['age']}"></td>
        </tr>
        <tr>
            <td>介绍</td>
            <td th:text="${user.getDetail()}"></td>
        </tr>
    </table>
    
  • List集合

    ​ 因为List集合是个有序列表,需要遍历List对其中对象取值,而遍历需要用到标签:th:each,具体使用为<tr th:each="item:${userlist}">,可以类比for-each理解。其中的item相当于每次遍历的对象名,在作用域可以直接使用;而userlist是在Model中储存的List的名称。示例代码如下:

    <h2>List Collection<h2>
    <table border="1">
    	# 在该作用域内可以通过item操作list的每一项    
        <tr th:each="item:${userlist}"> 
            <td th:text="${item}"></td>
        </tr>
    </table>
    
  • Map集合:

    • 取值:

      ​ 很多时候我们不存JavaBean而是将一些值放入Map中,再将Map存在Model中,我们就需要对Map取值。对于Map取值可以通过${Map名['key']}来进行取值。也可以通过${Map名.key}取值,也可以使用${map.get('key')}来取值。示例代码如下:

      <h2>Map Collection</h2>
      <table border="1">
          <tr>
              <td>place:</td>
              <td th:text="${map.get('place')}"></td>
          </tr>
          <tr>
              <td>feeling:</td>
              <td th:text="${map['feeling']}"></td>
          </tr>
      </table>
      
    • 遍历:

      ​ 如果说你想遍历Map获取它的key和value那也是可以的,这里就要使用和List相似的遍历方法,使用th:each="item:${Map名}"进行遍历,在下面只需使用item.keyitem.value即可获得值。示例代码如下:

      <h2>Map Collection</h2>
      <table border="1">
          <tr th:each="item:${map}">
              <td th:text="${item.key}"></td>
              <td th:text="${item.value}"></td>
          </tr>
      </table>
      

2.5 选择变量表达式 *{…}

​ 变量表达式不仅可以写成${…},而且还可以写成*{…}。但是,有一个重要的区别:星号语法对选定对象而不是整个上下文评估表达式。也就是说,只要没有选定的对象,$​{…}*{...}的语法就完全一样。

​ 什么是选定对象?使用th:object属性的表达式的结果。就可以选定对象,示例代码如下:

<div th:object="${user}">
    <p>Name: <span th:text="*{name}">abc</span>.</p>
    <p>Age: <span th:text="*{age}">18</span>.</p>
    <p>Detail: <span th:text="*{detail}">demo1</span>.</p>
</div>

​ 上面的代码如果不使用选定对象,完全等价于:

<div >
    <p>Name: <span th:text="*{user.name}">abc</span>.</p>
    <p>Age: <span th:text="${user.age}">18</span>.</p>
    <p>Detail: <span th:text="${user.detail}">demo2</span>.</p>
</div>

2.6 消息表达 #{…}

文本外部化是从模板文件中提取模板代码的片段,以便可以将它们保存在单独的文件(通常是.properties文件)中,文本的外部化片段通常称为消息(Message)

​ 通俗易懂的来说#{…}语法就是用来读取配置文件中数据的。在Thymeleaf你可以使用#{...}语法获取消息,具体实例代码如下:

  1. 首先在templates目录下建立messageDemo.yaml,并且写入以下内容:

    zzay.nane: zzay
    zzay.age: 20
    
    province: Guangdong
    
  2. application.yaml中加入以下内容:

    spring.messages.basename: templates/messageDemo
    

​ 这样我们就可以在Thymeleaf中读取配置文件,完整代码如下:

<h2>Message</h2>
<table border="1">
    <tr>
    	<td>name</td>
    	<td th:text="#{zzay.name}"></td>
    </tr>
    <tr>
    	<td>age</td>
    	<td th:text="#{zzay.age}"></td>
    </tr>
    <tr>
    	<td>province</td>
    	<td th:text="#{province}"></td>
    </tr>
</table>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值