目录
thymeleaf是一个模板引擎,是用来在Spring Boot中代替JSP的
引用thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
控制thymeleaf的版本号(thymelaf3以上的话,layout必须2以上才支持)
<properties>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
thymeleaf默认的路径是classpath://templates,必须是这个路径才能识别
我们在templates文件夹下面新建一个Vae.html,然后在Controller里面写一个方法去调用这个html
@RequestMapping("/Vae")
public String thymeleafTest(){
return "Vae";
}
点击运行,如图:
完美,我们已经新建了一个最简单的thymeleaf了
可以去官网下载文档查看
@RequestMapping("/Vae")
public String thymeleafTest(Map<String,Object> map){
map.put("hello","你好");
return "Vae";
}
前端的html需要做两个地方
<html xmlns:th="http://www.thymeleaf.org">
<div th:text="${hello}">欢迎</div>
写完之后,整个前端html就是这样
<html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>thymeleaf许嵩</h1>
<div th:text="${hello}">欢迎</div>
</body>
</html>
重启,再来访问,如图:
非常好,写th:text后面的${},让我想起来了JSP里面的EL。可以发现我
含有thymeleaf语法的html文件只有经过thymeleaf模板解析之后生效,项目之外就变成一个普通的HTML了
<div id="${hello}" class="${hello}" th:text="${hello}"></div>
${}:这个我们已经用过了,就是取值的
*{}:这个是代指${},例如Person类有name属性,${Person.name}=*{name}
#{}:获取国际化内容
@{}:定义url的,例如 @{https://localhost:8080(id=${Id})}
~{}:片段引用表达式
原文:https://www.cnblogs.com/yunquan/p/10344449.html