thymeleaf 语法|学习笔记

简介: 快速学习 thymeleaf 语法

开发者学堂课程【SpringBoot快速掌握 - 核心技术 thymeleaf 语法】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址https://developer.aliyun.com/learning/course/612/detail/9243


thymeleaf 语法

内容介绍: 

一、 Thymeleaf 使用

二、 Thymeleaf 语法规则

 

一、Thymeleaf使用

configurationProperties (prefix = "spring.thymeleaf)

public class ThymeleafProperties {

private static final Charset DEFAULT_ EMCODING - Charset.forName ("UTF-8");

private static final MNimeType DEFAULT_CONTENT_TYPE = NimeType.valueOf("text/html");

public static final Striing DEFAULT_PREFIX ="classpath:/templates/";

//默认前置

public static final String DEFAULT_SUFFIX- ".html";

//默认后置

//只要我们把 HTML  页面放在classpath:/templates/, thymeleaf就能自动渲染;

 controller 中写一个请求:

@RequestMapping("/success")

public String success{

//cLasspath:/templatesysuccess.html

return "success";

}

新建一个 success.html 文件

!DOCTYPE htm1>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</tit1e>

</head>

<body>

<h1>成功!k/h1>

</body>

</htm1>

运行在浏览器查看:localhost:8080/success

查看结果为:成功!

这个功能就是 thymeleaf 帮我们实现的

1、导入 thymeleaf 的名称空间

<html lang="en" xmlns:th="http://www.thymeleaf.ong"">

2、使用 thymeleaf 语法;

Controller  success 代码:

/查出一些数据,在页面展示

@RequestMapping("/suecess")

public String success(Map<String,0bject> map){

map.put( "he1lo","你好");

return "success";

}

Html 文件内容:

< !DOCTYPE html>

<html langm"en” xmlns:th=“http:// wnwnw.thymeleaf.org">

<head>

<meta charset-"UTF-8">

<title>Title</title>

</head>

<body>

<h1>成功!</h1>

<!--th:text将 div 里面的文本内容设置为${ hello }--->

<div th:text="${hello}">

这是显示欢迎信息

</div>

</body>

</html>

直接启动访问

返回成功!

你好

表示取值成功

 

二、Thymeleaf语法规则

1 、 th:text;改变当前元素里面的文本内容;

可以用th  :任意 html 属性;来替换原生属性的值

例如:<div id="div01"elass="myDiv" th:id="${hello}

Fragment inclusion片段包含:jsp:include

th: insert

th: replace

Fragment iteration//遍历:c:forEach

Th:each

Conditional evaluation

条性判断:c:if

th :if

th: unless

th : switch

th: case

Local variable definition

声明变量,c:set

th: object

th :with

General attribute modification

任意属性修改支持prepend, append

th: attr

th: attrprepend

th: attrappend

Specific attribute modification

修改指定属性默认值

th:value

th:href

th:src

Text ( tag body modification )//修改标签体内容

th : text//转义特殊字符

th : utext//不转义特殊字符

Fragment specification//声明片段

th:fragment

Fragment removal

2、表达式?

Simple expressions:(表达式语法)2

Variable Expressions: $..}: 获取变量值;OGNL,

3、获取对象的属性调用方法

4、使用内置的基本对象:

#ctx : the context object.

#vars: the context wariables.

#locale : the context locale.

#request : (only in Meb Contexts) the HttpServletRequest object.

#response : (only in web Contexts)the HttpServletResponse object.

#session:(only in Meb Context5)the HttpSession object.

#servletContext :(only in web Contexts) the ServletContext object.

怎么用:${session.foo}

5.内置的一些工具对象:

#execInfo : information about the template being processed.

#messages : methods for obtaining externalized messages inside variables expressions,in thesame way as they would be obtained using #{….} syntax.

#uris : methods for escaping parts of URLS/URIS

#conversions : methods for executing the configured conversion service (if any).

#dates : methods for java.uti1.Date objects: formatting,component extraction,etc.#calendars : analogous to

#dates , but for java.util.calendar objects.

#numbers : methods for formatting numeric objects.

#strings : methods for String objects: contains,startsiwith,prepending /appending, etc.

#objects :methods for objects in general.

#bools : methods for boolean evaluation.

#arrays : methods for arrays.

#lists : methods for list5.# sets : methods for setsI

#mapS : methods for maps.

#aggregates : methods for creating aggregates on arrays or collections.

#ids ; methods for dealing with id attributes that might be repeated (for example,as aresult of an iteration).

Selection Variable Expressions:*...):选择表达式:和$(在功能上是一样;

补充:配合 th;object=“${Session.user}:进行使用

<div th:object="${SeSsion.user}”>

<p>Name:<span th:text="*{firstName}">sebastian</span>-</p>

<P>Surname:cspan th:text="*{lastName ] ">pepper</span>.</P>

<p>Nationality:<spanth:text="*{nationality}">Saturn</span>.</P>

</div>

Message Expressions: #{...}:获取国际化内著

Link URL Expressions: @[..}: 定义URL;

@{/order/ process(execId=s{execId],execType="FAST)3

示例:

<!-- 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?order Id=3'(plus rewriting)-->

<a href="details.htrl" th:href="(/order /details(orderId=$[o.id])] "-view</a>

<!-- will produce '/gtvg/order /3/details' (plus rewriting) -->

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

Fragment Expressions: ~{..]:片段引用表达式

<div th:insert="-{commons :: main]">...</div>

其他用法:

Literals( 字面量 )

Text literals: "one text', 'Another one!’ .nMumber literals:e , 34 , 3.0 ,12.3 l

Boolean literals: true , false

Mull literal: null

Literal tokens: one , sometext , main .

Text operations:(文本操作)

String concatenation:

Literal substitutions: /The name is ${name}

Arithmetic operations:(数学运算)

Binary operators:+,-, *,/,%Minus sign(unary operator):

Boolean operations:(布尔运算)

Binary operators: and , or

Boolean negation (unary operator): !,not

Comparisons and equality:(比较运算)

Comparators: >,< , >-, <- ( gt , lt , ge ,le )

Equality operators: =- , != (eq , ne )

Conditional operators;条件运算(三元运算符)

If-then:(if)?(then)

If-then-else:(if) ?(then) : (else)Default:(value) ?: (defaultvalue)

Special tokens:|

No-operation: _

6.常见场景调用:

Controller:

//查出用户数据,在页面展示

@RequestMapping("/suecess")

public String success(Map<String,0bject> map){

map.put("he11o" , "<h1>你好</h1>");

map.put("users",Arrays.aslist("zhangsan", "lisi" , "wangwu"));

return "success";

}

Success.html

<!DOCTYPE htm1>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</tit1e>

</head>

<body>

<h1>成功!k/h1>

<hr/>

<div th:text="${hello}"></div>

<div th:utext="${hello]"></div><hr/>

<! --th:each每次遍历都会生成当前这个标签:3个h4 -->

<h4 th:text="${user}" th:each="user:${users}"></h4>

<hr/>

<h4>

<span th:each="user:${users} ">[[${user]]</span>

</h4>

</body>

</htm1>

重新启动运行显示出正确结果表示模板引擎使用成功

相关文章
|
8月前
|
容器
Thymeleaf $/*/#/@语法
Thymeleaf $/*/#/@语法
|
2月前
|
前端开发 JavaScript 索引
Thymeleaf基础语法讲解【详解版】
该内容介绍了Thymeleaf模板引擎的一些基本表达式和语法。主要包括: 1. 变量表达式 `${}` 和 `*{}`,用于获取对象属性,`*{}` 需先通过 `th:object` 指定对象。 2. 链接表达式 `@{}`,用于构建应用路径并引入静态资源,但可能暴露版本号带来安全问题。 3. 迭代循环使用 `th:each`,可获取状态变量如索引、序号、奇偶性等。 4. 条件判断用 `th:if` 和 `th:unless`,基于不同类型的值进行逻辑判断。 示例代码包括了遍历集合、设置表单输入值、条件渲染等场景。
|
2月前
|
XML 前端开发 Java
Spring Boot的Web开发之Thymeleaf模板引擎的解析及使用(Thymeleaf的基础语法以及常用属性)
Spring Boot的Web开发之Thymeleaf模板引擎的解析及使用(Thymeleaf的基础语法以及常用属性)
82 0
|
2月前
|
前端开发 Java Linux
Thymeleaf - 语法使用详解
Thymeleaf - 语法使用详解
45 0
|
7月前
模板引擎基本语法
模板引擎基本语法
|
8月前
|
缓存
Thymeleaf参考手册
Thymeleaf参考手册
|
11月前
|
XML 移动开发 JSON
Thymeleaf简介-HelloWorld基本语法:
Thymeleaf简介-HelloWorld基本语法:
60 0
|
前端开发 Java
thymeleaf 入门篇(一),简单语法介绍
thymeleaf 入门篇,基本语法介绍
157 0
|
开发框架 前端开发 JavaScript
FreeMarker的基本语法
FreeMarker的基本语法
162 0
FreeMarker的基本语法