thmeleaf模板引擎使用总结

简介: thmeleaf模板引擎使用总结

一、介绍

1、模板引起

开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。

简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较于其他的模板引擎,它有如下四个极吸引人的特点:

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

2、官网地址

https://www.thymeleaf.org/

3、文档下载

链接:https://pan.baidu.com/s/19y_1U3kBvh0r-Qn9ZS7mDg

提取码:q7s2

二、基本语法标签

关键字 功能介绍 案例
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}">conten</p>
th:object 替换对象 <div th:object="${session.user}">
th:value 属性赋值 <input th:value="${user.name}" />
th:with 变量赋值运算 <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 设置样式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 点击事件 th:onclick="'getCollect()'"
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:case th:switch的一个分支 <p th:case="'admin'">User is an administrator</p>
th:fragment 布局标签,定义一个代码片段,方便其它地方引用 <div th:fragment="alert">
th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div>
th:selected selected选择框 选中 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}",此标签不太优雅,一般用的比较少。

显示详细信息

三、springboot整合thmeleaf

Springboot整合Thmeleaf_程序三两行的博客-CSDN博客

四、常见使用

1、th:each 嵌套、List中包含List对象

在thmeleaf页面渲染list数据的时候,list里面包含list,如何展示?

2、thymeleaf引入公共css、js

有时候很多css文件是公共的,我们必须要在每个html文件中引入它们,其实我们可以利用Thymeleaf的模板布局,把这些css文件抽出来,同时如果有某个html文件专属的css文件,还可在引入模板的基础上单独引入该css文件。

首先,建立一个公共文件layout.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_head(title,links)">
      <meta charset="UTF-8">
      <title th:replace="${title}">CSDN博客</title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
      <link rel="shortcut icon" th:href="@{/resources/images/logo_ico_16.ico}" />
      <link rel="stylesheet" th:href="@{/resources/css/index.css}"/>
      <link rel="stylesheet" th:href="@{/resources/iconfont/iconfont.css}">
     <link rel="stylesheet" th:href="@{/resources/css/common.css}"/>
     <th:block th:replace="${links}" />
</head>
<body>
  
</body>
</html>

上面的“<head th:fragment="common_head(title,links)">”即为定义好的css模板,其中title和links为两个动态传入的变量,而th:block会在links值为空时自动隐藏,这样就可以实现除了css模板中的css文件之外,需要再单独引入css和不需要引入单独css两种情况。使用方法如下:

一、需要单独引入css

在实际的html文件中加入:

<head th:replace="layout :: common_head(~{::title},~{::link})">
    <title>测试公共css引入</title>
    <link rel="stylesheet" th:href="@{/resources/css/detail.css}"/>
    <link rel="stylesheet" th:href="@{/resources/css/profile.css}"/>
</head>

其中的title会自动将css模板中的title替换,而里面的多个link标签(只有一个link标签也可)也会替换th:block标签

二、不需要单独引入css

在实际的html文件中加入:

<head th:replace="layout :: common_head(~{::title},~{})">
    <title>测试公共css引入</title>
</head>

这种情况其实就是将传入的第二个变量置为空

但是这两种情况title都是必须的

3、a连接带参数请求的两种方式

第一种:通过拼接字符串的方式

<a href="#" th:if="${pageInfo.hasNextPage}" th:href="@{'/admin/article/list?page='+${pageInfo.nextPage}}">下一页</a>

后台接收

第二种:通过restful的方式

<a href="/type/list/{id} (id=${t.id})">类别1</a>

后台接收

4、thymeleaf局部刷新

之前用thymeleaf一直只是在页面加载的时候利用thymeleaf的标签取值,而ajax加载的数据则需要使用js添加到html中,那我们如果需要动态得局部刷新数据,该如何操作呢?

方法:使用th:fragment fragment可以理解为一个代码模板,thymeleaf可以根据这个进行定位。

html代码

 

<div class="article_type" th:fragment="article_type">
    文章分类:
    <div th:each="articletype : ${articleTypes}">                      
      <label class="checkbox-inline">
          <input type="checkbox" th:text="${articletype.text}" id="inlineCheckbox1" value="option1"> 
      </label>
    </div>
 </div>

ajax请求

    $('#btn').click(function () {
        var url = '/blog/test';
        $.ajax({
            url: url,
            type: 'POST',
            success: function (data) {
                $(".article_type").html(data);
            }
        })
    })

后台请求

@RequestMapping(value="/test",method=RequestMethod.POST)
public String aaa(Model model) {
    List<ArticleType> articleTypes = articleTypeService.selectLeafArticleTypes();
    ArticleType a = new ArticleType();
    model.addAttribute("articleTypes",articleTypes);
        
    return "write_article::article_type";
}

注意返回值是write_article::article_type,write_article是视图名称(html文件名称),article_type是fragment的名称。这样就只是填充article_type的数据,而不用刷新整个页面,达到动态刷新的目的。

也可以使用load函数进行局部刷新

 

<script>
    $('#btn').click(function () {
        var url = '/blog/test';
        $('.article_type').load(url);
    });
</script>

5、thmeleaf页面如何通过js获取后端值

后台java代码

 @RequestMapping("/toWaitReferPage")
 public String toWaitReferPage(HttpServletRequest request, Integer pageType){
     request.setAttribute("pageType",pageType);
     return "waitrefer/waitReferPage";
 }

js中取值

<script th:inline="javascript">
    var message = [[${pageType}]];
    console.log(pageType);
</script>

只有使用了thmeleaf中的th:inline="javascript" 才能通过[[${}]] 解析后端返回的值

6、th:insert 、th:replace、 th:include、 th:block区别

th:insert   :保留自己的主标签,保留th:fragment的主标签。

th:replace :不要自己的主标签,保留th:fragment的主标签。

th:include :保留自己的主标签,不要th:fragment的主标签。(官方3.0后不推荐)

th:block</th:block>是Thymeleaf提供的唯一的一个Thymeleaf块级元素,其特殊性在于Thymeleaf模板引擎在处理th:block的时候会删掉它本身,标签本身不显示,而保留其内容

 

需要替换的片段内容:
<footer th:fragment="copy">
   <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script>
</footer>
 
导入片段:
 
  <div th:insert="footer :: copy"></div>
 
  <div th:replace="footer :: copy"></div>
 
  <div th:include="footer :: copy"></div>
  
 
结果为:
 
<div>
    <footer>
       <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script>
    </footer>  
</div>  
 
<footer>
  <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script>
</footer>  
 
<div>
  <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script>
</div>  

7、如何给点击函数传递多个参数

<h2 th:data-title ="${dep.depId}"
    th:onclick="'doThing('+${dep.id}+','+${1}+',this)'"
    th:text="${dep.name}+'('+${dep.status}+')'">
</h2>
 
 
 window.getCommonGoal = function (id, num, e) {
        var title = $(e).attr("data-title");
        //其他业务
        
  }

说明:

1.dep是后台传到前端的实体对象

2.th:data-title自定义的属性

3.点击事件可以传递可变的实体属性、固定值、this对象


相关文章
|
6月前
|
测试技术
33 # 基本模板引擎
33 # 基本模板引擎
28 0
|
5天前
|
Python
配置模板引擎
配置模板引擎。
13 3
|
5月前
|
前端开发 JavaScript Java
前端最常用的模板引擎-Handlebars
前端最常用的模板引擎-Handlebars
57 0
|
Java 程序员 Maven
模板引擎:第二章:Thymeleaf
模板引擎:第二章:Thymeleaf
132 0
模板引擎:第二章:Thymeleaf
|
XML Java 程序员
模板引擎:第一章:FreeMarker
模板引擎:第一章:FreeMarker
162 0
模板引擎:第一章:FreeMarker
|
Java 应用服务中间件
详解模板引擎二
详解模板引擎二
75 0
详解模板引擎二
|
设计模式 前端开发 Java
【JavaWeb】模板引擎Thymeleaf
内容提取出来单独的放在一个文件中,称为模板,对于一些动态的内容,可以将这些内容在模板中使用占位符占位,当服务器把这些动态的内容计算好了之后,就可以把模板中占位符替换成动态计算的结果,然后把组装好的HTML格式的字符串在返回给浏览器
【JavaWeb】模板引擎Thymeleaf
|
Java 程序员 Apache
模板引擎——FreeMarker初体验
FreeMarker 是一款模板引擎:一种基于模板的、用来生成输出文本(任何来自于 HTML格式的文本用来自动生成源代码)的通用工具。
|
存储 移动开发 缓存
26、模板引擎thymeleaf
模板引擎根据一定的语义,将数据填充到模板中,产生最终的HTML页面。模板引擎主要分两种:客户端引擎和服务端引擎。
160 0
26、模板引擎thymeleaf
|
开发框架 自然语言处理 安全
第21天:Web开发 Jinja2模板引擎
第21天:Web开发 Jinja2模板引擎
180 0
第21天:Web开发 Jinja2模板引擎

热门文章

最新文章