thymeleaf简用

Thymeleaf 常用语法快速入门

SpringBoot中Thymeleaf 快速入门

Thymeleaf 是现代化服务器端的Java模板引擎,不同与JSP和FreeMarker,Thymeleaf的语法更加接近HTML,并且也有不错的扩展性和兼容性。

1、Maven引入

在 pom.xml 文件引入依赖

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

2、Controller

package com.huven.springboot.comtroller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * Created by v20 Luna on 2019/11/26 14:54
 */
@Controller
public class UserController {

    @GetMapping("/user")
    public String Hello(Model m){
        m.addAttribute("msg","Hello Thymeleaf");
        return "user";
    }
}

3、html

html 文件在 resource/templates 下面创建

注意: html标签一定要引入 xmlns:th="http://www.thymeleaf.org"

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Hello User</h1>
    <p th:text="${msg}"></p>
</body>
</html>

二、Thymeleaf 语法

1 text value string 操作

我的 Controller

@GetMapping("/test")
public String test(Model m){
    m.addAttribute("msg","Hello");
    return "test";
}

我的 html

<h1>text文字显示</h1>
<p th:text="${msg}"></p>

<h1>value给值</h1>
<input type="text" th:value="${msg}" disabled/>

<h1>string操作</h1>
是否为空:<span th:text="${#strings.isEmpty(msg)}" ></span><br>
是否包含指定的字符串:<span th:text="${#strings.contains(msg,'he')}" ></span><br>
是否以'h'字符串开头:<span th:text="${#strings.startsWith(msg,'h')}" ></span><br>
是否以'o'字符串结尾:<span th:text="${#strings.endsWith(msg,'o')}" ></span><br>
返回字符串的长度:<span th:text="${#strings.length(msg)}" ></span><br>
查找字符串的位置,获取'h'下标:<span th:text="${#strings.indexOf(msg,'h')}" ></span><br>
截取字符串:<span th:text="${#strings.substring(msg,2)}" ></span><br>
截取字符串:<span th:text="${#strings.substring(msg,1,3)}" ></span><br>
字符串转大写:<span th:text="${#strings.toUpperCase(msg)}" ></span><br>
字符串转小写:<span th:text="${#strings.toLowerCase(msg)}" ></span><br>

打开浏览器输出结果

text文字显示
Hello

value给值
string操作

是否为空:false
是否包含指定的字符串:false
是否以'h'字符串开头:false
是否以'o'字符串结尾:true
返回字符串的长度:5
查找字符串的位置,获取'h'下标:-1
截取字符串:llo
截取字符串:el
字符串转大写:HELLO
字符串转小写:hello

2 Date操作

controller

@GetMapping("/date")
public String date(Model m){
    m.addAttribute("date",new Date());
    return "date";
}

html

<h1>Date处理</h1>
格式化日期(浏览器的标准): <span th:text="${#dates.format(date)}" ></span><br>
格式化日期(自定义): <span th:text="${#dates.format(date,'yyyy年MM月dd日 HH时mm分ss秒')}" ></span><br>
日期获取年份: <span th:text="${#dates.year(date)}" ></span><br>
日期获取月份: <span th:text="${#dates.month(date)}" ></span><br>
日期获取日: <span th:text="${#dates.day(date)}" ></span><br>
日期获取小时: <span th:text="${#dates.hour(date)}" ></span><br>
日期获取分钟: <span th:text="${#dates.minute(date)}" ></span><br>
日期获取秒数: <span th:text="${#dates.second(date)}" ></span><br>
日期获取毫秒值: <span th:text="${#dates.millisecond(date)}" ></span><br>

页面输出结果

Date处理

格式化日期(浏览器的标准): 2019年11月26日 下午04时41分27秒
格式化日期(自定义): 2019年11月26日 16时41分27秒
日期获取年份: 2019
日期获取月份: 11
日期获取日: 26
日期获取小时: 16
日期获取分钟: 41
日期获取秒数: 27
日期获取毫秒值: 890

3 if switch使用

controller

@GetMapping("/testIf")
public String testIf(Model m){
    m.addAttribute("age",18);
    m.addAttribute("sex","男");
    return "testIf";
}

html

<h1>If测试</h1>
<span th:if="${age} lt 16">你已经不是青少年了</span><br/>
<span th:if="${age} ge 18">你已经成年了</span><br/>

<h1>switch测试</h1>
<span th:switch="${age}">
    <span th:case="16">16岁</span>
    <span th:case="17">17岁</span>
    <span th:case="18">18岁</span>
    <span th:case="19">19岁</span>
    <span th:case="20">20岁</span>
</span>
Thymeleaf 常用比较符号
比较符号解释
lt 小于 <
gt 大于 >
eq 等于 ==
le 小于等于 <=
ge 大于等于 >=

页面输出结果

If测试

你已经成年了

switch测试
18岁 

4 each 遍历list中的对象

map集合的话也是一样的

controller

@GetMapping("/each")
public String each(Model m){
    ArrayList<User> list = new ArrayList<User>();
    list.add(new User(1,"小明","男",18));
    list.add(new User(2,"小红","女",17));
    list.add(new User(3,"小花","女",18));
    m.addAttribute("list",list);
    return "each";
}

html

<h1>each遍历</h1>
<p>写法一</p>
<table border="1">
    <tr th:each="user : ${list}">
        <td th:text="${user.getId()}"></td>
        <td th:text="${user.getName()}"></td>
        <td th:text="${user.getSex()}"></td>
        <td th:text="${user.getAge()}"></td>
    </tr>
</table>

<p>写法二</p>
<table border="1">
    <tr th:each="user : ${list}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.sex}"></td>
        <td th:text="${user.age}"></td>
    </tr>
</table>

页面输出:

each遍历

写法一
1 	小明 	男 	18
2 	小红 	女 	17
3 	小花 	女 	18

写法二
1 	小明 	男 	18
2 	小红 	女 	17
3 	小花 	女 	18

5 测试作用域

1、Request

2、Session

3、Attribute

controller

@GetMapping("/area")
public String area(HttpServletRequest request){
    request.setAttribute("req","我是request");
    request.getSession().setAttribute("ses","我是session");
    request.getServletContext().setAttribute("att","我是attribute");
    return "area";
}

html:

<h1> area 测试,三大作用域</h1>
<h2>request</h2>
1<p th:text="${req}"></p>
2<p th:text="${#request.getAttribute('req')}"></p>
3<p th:text="${#httpServletRequest.getAttribute('req')}"></p>

<h2>session</h2>
1<p th:text="${ses}"></p>
2<p th:text="${#httpSession.getAttribute('ses')}"></p>
3<p th:text="${#session.getAttribute('ses')}"></p>

<h2>attribute</h2>
1<p th:text="${att}"></p>
2<p th:text="${#servletContext.getAttribute('att')}"></p>

输出结果:

area 测试,三大作用域

request
1
我是request
2
我是request
3
我是request

session
1

2
我是session
3
我是session

attribute
1
2
我是attribute

注意: 这里发现 <p th:text="${ses}"></p> 是取不到 Session 和 Attribute 对象的

6 URL用法

html:

<h1> URL 的表示</h1>
<a href="http://www.baidu.com">百度-普通html写法</a><br/>
<a th:href="@{http://www.baidu.com}">百度-绝对路径</a><br/>
<p>-------------相对路径----------------</p>
<a th:href="@{/user}">相对路径</a>
<a th:href="@{~/user}">相对服务器的根目录</a>
<a th:href="@{/user(id=6,name=wang)}">相对路径+传参数</a>

实测都可以访问!

=====================================================

 

 

 

=============================--------------------------

Thymeleaf菜鸟教程

小曦阳哟 2017-06-06 15:30:39 10038 收藏 10
展开
1. Thymeleaf概述
Thymeleaf是一个Java模板引擎,支持html、xml、text、javascript、css、raw这几种模型。
使用Thymeleaf首先需要引入命名空间

<html xmlns:th="http://www.thymeleaf.org">
1
2. 基本使用方法
引用web静态资源
Thymeleaf通过”@{}”来引用web静态资源,例如:
<script th:src="@{bootstrap/js/boostrap.min.js}"></script>
1
访问model模型中的数据,例如访问一个user对象的name属性
<span th:text="${user.name}"></span>
1
数据迭代
例如迭代一个userlist集合
<tr th:each="user : ${userlist}">
<td th:text="${user.name}">tyrone</td>
<td th:text="${user.age}">18</td>
</tr>
1
2
3
4
使用th:each做循环迭代,并使用${对象.属性}来访问具体的值

判断是否为空
<tr th:if="${messages.empty}">
<td colspan="3">No messages</td>
</tr>
1
2
3
在Javascript中访问model模型数据
<script th:inline="javascript">
var user = [[${user}]]
console.log(user.name + "\t" + user.age);
</script>
1
2
3
4
通过添加th:inline=”javascript”到script标签来访问model模型数据
通过”[[${}]]”这种格式来获取具体的值

==================================================

================================================

=======================

thymeleaf快速入门教程

石奈子 2017-07-21 10:19:20 111476 收藏 28
展开
thymeleaf教程
本教程涵盖了常见的前端操作,比如,判断,循环,引入模板,常用函数(日期格式化,字符串操作)下拉,js和css中使用,基本可以应对一般场景。

怎么使用?
前端html页面标签中引入如下:

<html xmlns:th="http://www.thymeleaf.org">
1
表达式
简单表达式
可用值表达式(后台设置): ${…}
所有可用值表达式: *{…}

比如*{name} 从可用值中查找name,如果有上下文,比如上层是object,则查object中的name属性。

消息表达式: #{…}
国际化时使用,也可以使用内置的对象,比如date格式化数据

链接表达式: @{…}
用来配合link src href使用的语法
片段表达式: ~{…}
用来引入公共部分代码片段,并进行传值操作使用的语法。
文字

文本: ‘one text’,’another text’,…
数字: 1,2,1.2,…
布尔: true,false
空值:null
单词: something,main,name,…
文本操作

链接:+
替换:|The name is ${name}|
html
<a href="" th:href="@{|/name/${test.size()}|}">链接地址:</a>
//渲染后的结果
<a href="/name/3">链接地址:</a>
数学操作

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

一元 : and or
二元 : !,not
比较

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

If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
无操作
使用_ 来禁止转义。

支持的操作
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
1
布尔类型

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
1
判断操作
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;
}
1

@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";
}
1
前端语法
<table>
<thead>
<th></th>
</thead>
<tbody>
<tr th:each="test:${test}">
<!--判断成绩-->
<td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
<td th:if="${test.Score} ge 60 and ${test.Score} le 70">中</td>
<td th:if="${test.Score} gt 70 and ${test.Score} le 80">良</td>
<td th:if="${test.Score} gt 80 and ${test.Score} le 90">优</td>
<td th:if="${test.Score} gt 90 and ${test.Score} le 100">超级优秀</td>
</tr>
<br>
<tr th:each="test:${test}">
<!--判断成绩 一般只有两种情况的时候可以使用这种方式-->
<td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
<!--除了这些条件之外的-->
<td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td>
</tr>
<tr th:each="test:${test}">
<td th:switch="${test.male}">
<span th:case="1">男</span>
<span th:case="2">女</span>
<!--其他情况-->
<span th:case="*">未知</span>
</td>
</tr>

</tbody>
1
结果


超级优秀


及格
及格


模板操作
主要引入公共头部和底部相关代码使用 ,当然也可以其他地方使用
- 示例

底部模板代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<body>
<div th:fragment="footer">
© 2016 xxx
</div>
</body>
</html>
1
2
3
4
5
6
7
8
Springboot整合引入模块

<!--写入绝对路径即可引入 -->
<div th:include="/back/import/footer :: footer"></div>
1
2
文本和带格式文本
用来输入内容到标签内部,而不是attr中。分为th:text和th:utext两种,后者可以渲染文本中的标签。
- th:utext

map.put("msgutext","<b>1111</b>");
1
<div th:utext="${msgutext}"></div>
1
2
结果:被渲染了

th:text
<div th:text="${msgutext}"></div>
1
2
结果:原样输出到页面。

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

<th:block th:with="score=${test.Score}">
<td th:if="${score} ge 60">及格啦</td>
</th:block>
1
2
3
循环
遍历元素

示例:
<tr th:each="test:${test}">
<td th:text="${test.Score}"></td>
</tr>
1
2
3
循环下标判断
List<String> list=new ArrayList<String>();
list.add("1s");
list.add("2s");
list.add("3s");
map.put("list",list);
1
2
3
4
5
<th:block th:each="mylist,iterStat:${list}">
111
<span th:text="${mylist}"></span>
<th:block th:if="${iterStat.index le 1}">
<span th:text="${mylist}"></span>
</th:block>
</th:block>
1
2
3
4
5
6
7
常用操作
日期格式化
<td th:text="${#dates.format(content.createDate,'yyyy-MM-dd HH:mm:ss')}" ></td>
1
字符截取长度
<td th:if="${#strings.length(content.title) gt 5 } " th:text="${#strings.substring(content.title,0,5) + '…'}"></td>
1
下拉选择
<select name="subId" id="subId" lay-verify="" >
<option value="">请选择</option>
<option th:each="channelsub:${subchannels}" th:selected="${channelsub.id == subId}" th:value="${channelsub.id}" th:text="${channelsub.name}"></option>
</select>
1
2
3
4
js取值
有时候需要传递参数到js中,按如下方式:

<script th:inline="javascript" >
var size= [[${test.size()}]];
console.info(size)
</script>
1
2
3
4
进阶
ps: 下面涉及到thymeleaf的语法出,可以替换成其他thymeleaf的语法来用
<script th:inline="javascript" >
//尺寸等于3时打印日志..
/*[# th:if="${test.size() eq 3}"]*/
console.info('Welcome admin');
/*[/]*/
</script>
1
2
3
4
5
6
css取值
首先需要后台设置classname、align的值,之后按如下方式:

<style th:inline="css">
.[[${classname}]] {
text-align: [[${align}]];
}
</style>
1
2
3
4
5
结语
thymeleaf还有很多其他的语法,这里只是做个入门,方便上手,详细教程请参阅 官方教程。当然也可以加群交流。

posted @ 2020-04-23 09:05  不良小帅  阅读(447)  评论(0编辑  收藏  举报