开发一般咱们都会使用模板引擎,好比:JSP、Velocity、Freemarker、Thymeleaf等等不少,那么模板引擎是干吗用的?html
模板引擎,顾名思义,是一款模板,模板中能够动态的写入一些参数,咱们将这些参数在代码中传入,以保证数据在页面的动态调用,这就是引擎要作的,页面和数据的动态传输模板。git
SpringBoot官方为咱们推荐的是Thymeleaf,让咱们来看看这款引擎哪里出彩:github
语法相对更简单,且功能强大;spring
直接在pom中添加便可json
<dependency> <!-- 先后端分离的模板引擎 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
然而目前来看,官方默认的模板引擎的版本有些旧,咱们须要变动下版本,那么只须要修改下version就能够了,能够去Thymeleaf的官网或者github上看一下最新的版本,引入便可,好比:后端
(不知道怎么添加的,自学pom.xml去,这里不作介绍,毕竟是进阶的文章)session
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <!-- 布局功能的支持程序,若thymeleaf 3主程序 , layout须要2以上版本 --> <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
首先咱们须要关注下,SpringBoot若想使用模板引擎,那么须要将html文件放入在指定的文件夹才能被识别,SpringBoot这里默认识别的动态资源文件夹是app
"classpath:/templates/"
因此咱们须要将html页放到这个文件夹中才能别自动识别和渲染。前后端分离
Thymeleaf的语法说简单,是由于它彻底能够按照html的方式来编写,举例 “success.html”spring-boot
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>成功</h1> </body> </html>
而后咱们来写一个controller,访问下这个页面看看是否OK:(以前咱们学习了在@Controller的类内加入@ResponseBody能够访问json资源,这里不加的话,就是访问页面了)
@Controller public class SuccessController { @GetMapping("/success") public String sucTest(){ return "success"; } }
来看访问结果:
很好,完成了咱们的第一步实践。
推荐:下载官方文档,教你怎么用thymeleaf,如图:(官方连接地址)
@Controller public class SuccessController { @GetMapping("/success") public String sucTest(Map<String,Object> map){ map.put("hello","你好"); return "success"; } }
1.首先在html中加入 xmlns:th="http://www.thymeleaf.org" ,这个能够帮助咱们引导使用thymeleaf。
2.而后使用thymeleaf语法,在须要引值的地方添加th:text,这里表示须要引入文本,使用${xx},就是咱们代码中写的值,这里填的是hello,页面中应当返回的就是“你好”
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>成功</h1> <div th:text="${hello}">这是没有引擎展现的数据</div>
</body>
</html>
最后,咱们来看是否展现成功:
很好,没有问题,hello的值是“你好”,成功展现。
另外,咱们看到,在html中的div中,咱们还有一段文字,没有展现,这个文字是在没有引入引擎的时候展现的,也就是先后端分离的做用了
以上就是一些简单的使用,接下来,咱们看下其余实现,也就是Thymeleaf的语法还有些什么。
好比:(能够看到,原生的属性,都替换成了hello的值)
<div id="abc" class="aaa" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是没有引擎展现的数据</div>
th:id="${session.abc} 或者 th:id="${string.tostring()}"
<div th:object="${odin.user}" th:text="${hello}">这是没有引擎展现的数据</div> <a th:id="*{name}"></a> <a th:id="*{sex}"></a> </div>
这里 * 就表示上边object定义的变量odin.user。其下边的*{name} 等同于 ${odin.user.name}
另外,还能够拼接咱们须要的url,如图:
还有不少后边会用到的表达式,
好比,字面量、文本操做(字符串拼接)、数学/布尔/比较/条件运算、特殊操做,参考文档来学习吧!