https://github.com/itwell/springboot-thymeleaf (原码下载)
引入 Thymeleaf 依赖
org.springframework.boot
spring-boot-starter-thymeleaf
创建模板文件
Thymeleaf demo
description字段值为:
这里显示的是 description 字段内容
controller
package com.itwell.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ThymeleafController {
@GetMapping("/thymeleaf")
public String hello(HttpServletRequest request, @RequestParam(value = "description", required = false, defaultValue = "springboot-thymeleaf") String description) {
request.setAttribute("description", description);
return "thymeleaf";
}
}
关闭缓存
# thymeleaf模板缓存 开发环境下推荐打开 实时看到页面的变化 spring.thymeleaf.cache=false#{} 消息表达式 在resource文件夹下创建 i18n文件夹 创建不同语言的配置文件
hello.properties
hello_en_US.properties
hello_zh_CN.properties
#i18n国际化 spring.messages.basename = i18n.hello模板文件测试
*{} 星号表达式 controller...
Book book = new Book();
book.setTitle("三国演义");
request.setAttribute("book", book);
html
*{}取的是${}里面的数据
${}取的是上下文里面的数据
相对的链接表达式
服务器相对
协议相对
绝对链接表达式
th:insert th:replace
新建一个footer.html
Title
© 2020
在thymeleaf.html 引入 footer.html
字面量
文本
...
数字
...
数字计算
...
布尔
真
null
th:class 条件运算符真
三元表达式
无操作
设置属性值no user authenticated
内置属性
自定义属性
固定布尔值
迭代器
ArrayListbooks = new ArrayList<>(); Book book1 = new Book(); book1.setTitle("水浒传"); Book book2 = new Book(); book2.setTitle("西游记"); Book book3 = new Book(); book3.setTitle("红楼梦"); Book book4 = new Book(); book4.setTitle("三国演义"); books.add(book1); books.add(book2); books.add(book3); books.add(book4);
遍历
状态变量
index count size current even/odd first last
| ... | default |
th:if
如果 boolean 是 true ,本句话就会显示
th:unless
如果 unless 是 false ,本句话就会显示
th:switch
显示a
显示b
显示c
引用片段th:fragment
定义片段
© 2020
引用片段
不使用th:fragment
定义片段
片段
引用片段
th:insert th:replace th:include
th:insert 将被插入内容连同标签 放入到主页面当中.
th:replace 将被插入内容连同标签 放入到主页面当中 但是会替换掉主页面的标签
th:include 类似于th:insert ,将被插入内容不包含标签 放入到主页面当中(3.x版本后,不在推荐使用)
| Order | Feature | Attributes |
|---|---|---|
| 1 | Fragment inclusion | th:insert th:replace |
| 2 | Fragment iteration | th:each |
| 3 | Conditional evaluation | th:if th:unless th:switch th:case |
| 4 | Local variable definition | th:object th:with |
| 5 | General attribute modification | th:attr th:attrprepend th:attrappend |
| 6 | Specific attribute modification | th:value th:href th:src ... |
| 7 | Text (tag body modification) | th:text th:utext |
| 8 | Fragment specification | th:fragment |
| 9 | Fragment removal | th:remove |
[[…]]或[(…)]分别对应于th:text和th:utext
[[…]]不会解析html标签
[(…)]会解析html标签
controller
request.setAttribute("msg", "great!");
html
表达式基本对象The message is "[(${msg})]"
The message is "[[${msg}]]"
#ctx :上下文对象。
${#ctx.request}
${#ctx.response}
${#ctx.session}
${#ctx.servletContext}
希望对热爱编程的小伙伴有所帮助,博学谷-IT在线教育培训机构-传智教育旗下IT在线学习平台



