https://www.cnblogs.com/jiangbei/p/8462294.html

一、概述

  1.是什么

    简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。

  2.feature

    1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

       2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
       3. Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

  3.文档

    官方教程http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#what-is-thymeleaf

    推荐教程http://blog.didispace.com/springbootweb/

         http://blog.csdn.net/u012706811/article/details/52185345

二、HelloWorld

  1.引入依赖

    springboot直接引入:

  <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

    非springboot项目使用如下依赖:

<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>2.1.4</version>
</dependency>

  默认的模板映射路径是:src/main/resources/templates,

  springboot1.4之后,可以使用thymeleaf3来提高效率,并且解决标签闭合问题,配置方式:

 <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- set thymeleaf version -->
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
<!--set java version-->
<java.version>1.8</java.version>
</properties>

   之前的model/modelMap/modelAndView等页面数据传递参考之前随笔:点击查看

    快速回顾:

model/modelMap/modelAndView

  2.配置thymeleaf视图解析器

    这点与springMVC是相类似的:

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end

    实际项目中可能会有不太严格的HTML格式,此时设置mode=HTML5将会对非严格的报错,可以参考以下配置:

spring.thymeleaf.mode=LEGACYHTML5
你可能会发现在默认配置下,thymeleaf对.html的内容要求很严格,比如<meta charset="UTF-8" />,
如果少最后的标签封闭符号/,就会报错而转到错误页。也比如你在使用Vue.js这样的库,然后有<div v-cloak></div>这样的html代码,
也会被thymeleaf认为不符合要求而抛出错误。 因此,建议增加下面这段: spring.thymeleaf.mode = LEGACYHTML5
spring.thymeleaf.mode的默认值是HTML5,其实是一个很严格的检查,改为LEGACYHTML5可以得到一个可能更友好亲切的格式要求。 需要注意的是,LEGACYHTML5需要搭配一个额外的库NekoHTML才可用。
  1. <dependency>
  2. <groupId>net.sourceforge.nekohtml</groupId>
  3. <artifactId>nekohtml</artifactId>
  4. <version>1.9.22</version>
  5. </dependency>
最后重启项目就可以感受到不那么严格的thymeleaf了。

  这样,需要的配置项如下:

# 一项是非严格的HTML检查,一项是禁用缓存来获取实时页面数据,其他采用默认项即可
thymeleaf:
mode: LEGACYHTML5
cache: false

  // 完整配置项参考类ThymeleafProperties

  3。编写控制器

/**
* 测试demo的controller
*
* @author zcc ON 2018/2/8
**/
@Controller
public class HelloController {
private static final Logger log = LoggerFactory.getLogger(HelloController.class); @GetMapping(value = "/hello")
public String hello(Model model) {
String name = "jiangbei";
model.addAttribute("name", name);
return "hello";
}
}

  4.编写模板html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<!--/*@thymesVar id="name" type="java.lang.String"*/-->
<p th:text="'Hello!, ' + ${name} + '!'">3333</p>
</body>
</html>

  其中,注释是通过alt+enter进行自动生成的,便于IDEA补全,如果不加,IDEA将会报错cannot reslove,

  当然也可以通过如下方式解决,解决之前推荐在maven项目中reimport一下!(据说新版本的IDEA中已经修复此问题,待更新至2017.3以后)

  5.测试

  

三、基础语法

  1.创建HTML

    由上文也可以知道需要在html中添加:

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

    这样,下文才能正确使用th:*形式的标签!

  2.获取变量值${...}

    通过${…}进行取值,这点和ONGL表达式语法一致!

  <!--/*@thymesVar id="name" type="java.lang.String"*/-->
<p th:text="'Hello!, ' + ${name} + '!'">3333</p>

   选择变量表达式*{...}

<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text={nationality}">Saturn</span>.</p>
</div>
等价于
<div>
<p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

    至于p里面的原有的值只是为了给前端开发时做展示用的.这样的话很好的做到了前后端分离。

    这也是Thymeleaf非常好的一个特性:在无网络的情况下也能运行,也就是完全可以前端先写出页面,模拟数据展现效果,后端人员再拿此模板修改即可!

  3.链接表达式: @{…} 

    用来配合link src href使用的语法,类似的标签有:th:hrefth:src

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --> 

<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->

<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<a href="details.html" th:href="@{order/{orderId}/details(orderId=${o.id})}">Content路径,默认访问static下的order文件夹</a>

  4.文本替换

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

  或者下面的表达方式:(只能包含表达式变量,而不能有条件判断等!)

<span th:text="|Welcome to our application, ${user.name}!|">

  5.运算符

    数学运算

  • 二元操作:+, - , * , / , %
  • 一元操作: - (负)

    逻辑运算

  • 一元 : and or
  • 二元 : !,not

    比较运算(为避免转义尴尬,可以使用括号中的英文进行比较运算!)

  • 比较:> , < , >= , <= ( gt , lt , ge , le )
  • 等于:== , != ( eq , ne )

    条件运算

  • If-then: (if) ? (then)
  • If-then-else: (if) ? (then) : (else)
  • Default: (value) ?: (defaultvalue)
  • 'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

    6.条件

   if/unless

   使用th:if和th:unless属性进行条件判断,th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

   switch

<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>

  7.循环

    通过th:each

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<!-- 不存在则忽略,显示hello null!(可以通过默认值进行设置)-->
<p th:text="'Hello ' + (${name}?:'admin')">3333</p>
<table>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
<tr th:each="emp : ${empList}">
<td th:text="${emp.id}">1</td>
<td th:text="${emp.name}">海</td>
<td th:text="${emp.age}">18</td>
</tr>
</table>
</body>
</html>

    后台:

@GetMapping(value = "/hello")
public String hello(Model model) {
List<Emp> empList = new ArrayList<>();
empList.add(new Emp(1, "校长", 24));
empList.add(new Emp(2, "书记", 28));
empList.add(new Emp(3, "小海", 25));
model.addAttribute("empList", empList);
return "hello";
}

    效果:

    

  更多循环深入,iterStat等示例,参考http://blog.csdn.net/sun_jy2011/article/details/40710429

  8.内置对象Utilites

    一般不推荐在前端进行这些处理,前端页面以减少逻辑为宜

#dates :

utility methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects.

#numbers :
utility methods for formatting numeric objects. #strings :
utility methods for String objects: contains, startsWith, prepending/appending, etc. #objects : utility methods for objects in general. #bools :
utility methods for boolean evaluation. #arrays : utility methods for arrays. #lists :
utility methods for lists. #sets :
utility methods for sets. #maps :
utility methods for maps. #aggregates :
utility methods for creating aggregates on arrays or collections. #messages :
utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{...} syntax. #ids :
utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

  常用示例:

/*
* Format date with the specified pattern
* Also works with arrays, lists or sets
*/
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')} /*
* Create a date (java.util.Date) object for the current date and time
*/
${#dates.createNow()} /*
* Create a date (java.util.Date) object for the current date (time set to 00:00)
*/
${#dates.createToday()}
/*
* Check whether a String is empty (or null). Performs a trim() operation before check
* Also works with arrays, lists or sets
*/
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)} /*
* Check whether a String starts or ends with a fragment
* Also works with arrays, lists or sets
*/
${#strings.startsWith(name,'Don')} // also array*, list* and set*
${#strings.endsWith(name,endingFragment)} // also array*, list* and set* /*
* Compute length
* Also works with arrays, lists or sets
*/
${#strings.length(str)} /*
* Null-safe comparison and concatenation
*/
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)} /*
* Random
*/
${#strings.randomAlphanumeric(count)}

  完整参考点击查看

四、常用标签

  

   // 类似于th:object和th:field等进行表单参数绑定还是很有用的!使用与注意事项,参见:这里

   参考博文https://www.cnblogs.com/hjwublog/p/5051732.html

Thymeleaf入门——入门与基本概述的更多相关文章

  1. 14 微服务电商【黑马乐优商城】:day01-springboot(Thymeleaf快速入门)

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) :day01-springboot(Thyme ...

  2. Thymeleaf从入门到精通

    什么是Thymeleaf 大家好,我是bigsai,今天我们来学习Thymeleaf,如果你对Thymeleaf比较陌生也不要紧,它很容易学习与理解,并有着自己鲜明的特色. 开始之前,我们依旧问一个问 ...

  3. Python3入门(一)——概述与环境安装

    一.概述 1.python是什么 Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. Python 是一种解释型语言: 这意味着开发过程中没有了编译这个环节.类似于PHP和 ...

  4. Thymeleaf入门入门入门入门入门入门入门入门入门入门入门

    Thymeleaf 官网部分翻译:反正就是各种好 Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎 Spring官方支持的服务的渲染模板中,并不包含jsp.而是Thymel ...

  5. 无废话SharePoint入门教程一[SharePoint概述]

    一.前言 听说SharePoint也有一段时间了,可一直处在门外.最近被调到SharePoint实施项目小组,就随着工作一起学习了一下实施与开发.但苦于网上SharePoint入门的东西实在太少,导致 ...

  6. Linux入门第一天——基本概述与环境搭建

     一.Linux简介 1.历史 Linux内核最初只是由芬兰人李纳斯·托瓦兹(Linus Torvalds)在赫尔辛基大学上学时出于个人爱好而编写的. Linux是一套免费使用和自由传播的类Unix操 ...

  7. [转]无废话SharePoint入门教程一[SharePoint概述]

    本文转自:http://www.cnblogs.com/iamlilinfeng/p/3026332.html 一.前言 听说SharePoint也有一段时间了,可一直处在门外.最近被调到ShareP ...

  8. Thymeleaf教程入门到深入1:基础介绍

    1 介绍 1.1 简介 Thymeleaf是一个用于Web和独立Java环境的模板引擎,能够处理HTML.XML.JavaScript.CSS甚至纯文本.能轻易的与Spring MVC等Web框架进行 ...

  9. 阶段3 3.SpringMVC·_01.SpringMVC概述及入门案例_01.SpringMVC概述及入门案例

    第二章 第三章 第四章 三层框架 springMvc是表现层

随机推荐

  1. HTML5 Canvas(实战:绘制饼图2 Tooltip)

    继上一篇HTML5 Canvas(实战:绘制饼图)之后,笔者研究了一下如何给饼图加鼠标停留时显示的提示框. Plot对象 在开始Coding之前,笔者能够想到的最easy的方式,就是给饼图的每一个区域 ...

  2. vue兄弟组件之前传信

    1.使用vuex 2.子传父,父传子 3.使用中央事件总线 1.新建一个js文件,然后引入vue 实例化vue 最后暴露这个实例 2.在要用的组件内引入这个组件 3.通过vueEmit.$emit(' ...

  3. 英语单词composing

    composing 来源——书籍Python.Crash.Course.2015.11 Using Individual Values from a List You can use individu ...

  4. MyBatis 中的#和$的区别

    #相当于对数据 加上 双引号,$相当于直接显示数据 #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号.如:order by #user_id#,如果传入的值是111,那么解析成sql时的 ...

  5. php实现进度条原理

    PHP实现进度条的原理: 模版替换,在页面设置一个标识,轮子自己的页面,不发请求给服务器,由服务器端获得进度,然后替换该页面标识,达到进度条效果. 页面代码: 1 2 3 4 5 6 7 8 9 10 ...

  6. Web截屏插件

    官方网站:http://www.ncmem.com 官方博客:http://www.cnblogs.com/xproer 产品首页:http://www.ncmem.com/webplug/scppr ...

  7. 【CF1257F】Make Them Similar【meet in the middle+hash】

    题意:给定n个数,让你给出一个数,使得n个数与给出的数异或后得到的数的二进制表示中1的数量相同 题解:考虑暴搜2^30去找答案,显然不可接受 显然可以发现,这是一个经典的meet in the mid ...

  8. 攻防世界 | level2

    # ! /usr/bin/env python # -*- coding:utf-8 -*- from pwn import * context.log_level = 'debug' elf = E ...

  9. oracle12.2 CDB PDB基本管理操作

    容器间切换 切换到对应的PDBSSQL> alter session set container=pdb1;Session altered.SQL> alter database open ...

  10. day34—JavaScript实现DOM操作

    转行学开发,代码100天——2018-04-19 1.通过JavaScript元素属性的操作 三种: window.onload =function(){ var oTxt = document.ge ...