thymeleaf的依赖导入
因为有人可能是初次使用thymeleaf简单说一下依赖导入,需要在maven项目下的pox.xml文件中导入依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
当然你也可以从Maven Repository中搜索thymeleaf来导入最新版本的依赖包。
另外这里最好在需要编辑的html页面中导入thymeleaf的命名空间,这样可以在编辑的时候出现thymeleaf的语法提示,具体代码如下。
<html xmlns:th="http://www.thymeleaf.org">
tips:如果使用的eclipse,则需要下载thymeleaf的插件。
具体参照如下步骤:
https://blog.csdn.net/windkiller_XiaoJian/article/details/81675225
至此我们已经可以使用thymeleaf了
thymeleaf的语法介绍
常用属性
th:任意html属性
th:insert(片段包含,等于jsp中的jsp:inculde)
th:each(遍历,等于jsp中的c:forEach)
th:if(判断,等于jsp中的c:if)
th:attr th:attrprepend th:attrappend (对任意属性修改,attrprepend在属性后追加,attrappend在属性前追加)
tips:th:任意html属性会覆盖原生属性的内容,如:
<h1 th:text="${hello}">成功!</h1>
在这段代码中使用th获取的hello值会覆盖成功!但是如果直接打开这个html文件显示的还是成功,因为没有走thymeleaf的渲染。
表达式语法
${…}:用来获取变量值
- 获取对象的属性,调用方法(常用)
- 使用内置的基本对象,如${session.foo}调用session域内容
- 一些内置工具对象
tips:${…}只能在th属性内使用,不可以直接放置在内容中,例:
//这个是错误的写法!
<h1>${hello}成功!</h1>
*{…}:选择表达式:和${}在功能上一样
- 补充就是可以配合th:object="${session.user}"来使用
<div th:object="${session.user}">
<h1 th:text="*{username}"></h1>
<h1 th:text="*{password}"></h1>
<h1 th:text="*{userPhone}"></h1>
</div>
<div>
<h1 th:text="${username}"></h1>
<h1 th:text="${password}"></h1>
<h1 th:text="${userPhone}"></h1>
</div>
//这两个是一样的效果
#{…}:获取国际化内容
@{…}:定义超链接
<a href="#" th:href="@{http://locahlhost:8080(username=${username})}"></a>
~{…}:片段引用表达式
下面是摘自thymeleaf使用手册的一段内容
Simple expressions:
Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL Expressions: @{...}
Fragment Expressions: ~{...}
Literals(字面量)
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null 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:(特殊操作)
Page 17 of 106
No-Operation: _
```