org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致我们修改页面不会立即被展现,因此我们关闭缓存。
关闭Thymeleaf的缓存
spring:
thymeleaf:
cache:
false
另外,修改完毕页面,需要使用快捷键:Ctrl + Shift + F9
来刷新工程。
我们准备一个controller,控制视图跳转:
@Controller
public class HelloController {
@GetMapping(“hello”)
public String show1(Model model){
model.addAttribute(“msg”, “Hello, Thymeleaf!”);
return “index”;
}
}
新建一个html模板:
语法说明:
Thymeleaf通过${}
来获取model中的变量,注意这不是el表达式,而是ognl表达式,但是语法非常像。不过区别在于,我们的表达式写在一个名为:th:text
的标签属性中,这个叫做指令
大家好
启动项目,访问页面:
动静结合:
Thymeleaf崇尚自然模板
,意思就是模板是纯正的html代码,脱离模板引擎,在纯静态环境也可以直接运行。现在如果我们直接在html中编写 ${}
这样的表达式,显然在静态环境下就会出错,这不符合Thymeleaf的理念。
Thymeleaf中所有的表达式都需要写在指令
中,指令是HTML5中的自定义属性,在Thymeleaf中所有指令都是以th:
开头。因为表达式${user.name}
是写在自定义属性中,因此在静态环境下,表达式的内容会被当做是普通字符串,浏览器会自动忽略这些指令,这样就不会报错了!
| 标签 | 作用 | 样例 |
| — | — | — |
| th:id | 替换id | <input th:id="${user.id}"/>
|
| th:text | 文本替换 | <p text:="${user.name}">name</p>
|
| th:utext | 支持html的文本替换 | <p utext:="${htmlcontent}">content</p>
|
| th:object | 替换对象 | <div th:object="${user}"></div>
|
| th:value | 属性赋值 | <input th:value="${user.name}" >
|
| th:with | 变量赋值运算 | <div th:with="isEven=${user.age}%2==0"></div>
|
| th:style | 设置样式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
|
| th:src | 替换资源 | <script type="text/javascript" th:src="@{index.js}"></script>
|
| th:onclick | 点击事件 | th:onclick="'getCollect()'"
|
| th:href | 替换超链接 | <a th:href="@{index.ht