Thymeleaf是前端开发模板,springboot默认支持。前端模板用法大多数是类似的jsp、thymeleaf、vue.js都有while\for\if\switch等使用,页面组件化等。
1.前端模板区别
jsp是前后端完全不分离的,jsp页面写一堆Java逻辑。
 thymeleaf好处是html改造方便,可以独立预览。vue.js是完全前后端分离的。
2.快速入门
(1)新建springboot项目
# 关闭Thymeleaf的缓存 spring.thymeleaf.cache=false
(可忽略)可以开启热部署,maven,引入devtool,配置SpringbootApplication,Running Application
Update Policies ,选择 Update resources
准备index.html
<html xmlns:th="http://www.thymeleaf.org">
th:text ="${name}"
创建Controller
@GetMapping("/index")
String index(Model model){
     model.setAttribute("name","html");
        return "index"
 }
3.Thymeleaf语法
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title></title>
</head>
<body>
    <!--通过${}来获取model中的变量,是ognl表达式-->
    <p th:text="${name}">测试</p>
    <!--字符串拼接-->
    <p th:text="|测试-${name}|"></p>
    <!--对象,星号选择-->
    <ul th:object="${user}">
        <li th:text="*{title}"></li>
        <li th:text="*{name}"></li>
        <li th:text="*{age}"></li>
        <!--if判断-->
        <li th:if="*{isVip}=='1'" th:text="*{isVip}"></li>
        <!--追加css-->
        <li th:styleappend="*{isVip}=='1' ? 'margin-top:50px' : _"></li>
        <li th:classappend="*{isVip}=='1' ? 'css_test' : _"></li>
    </ul>
    <style>
    .css_test{
        margin-top:50px;
        background-color: red;
    }
    </style>
    <!--内联js-->
    <script th:inline="javascript">
        var name =/*[[${user.name}]]*/ '李四';
        console.log(name);
    </script>
    <!--内嵌变量 dates,${#dates.format(date, 'dd/MMM/yyyy HH:mm')}-->
    <!--组件-->
    <div th:replace="include::body"></div>
</body>
</html>运行效果

 3.引入静态文件
 th:href="@{/blog/yummy-jekyll/plugins/jquery/dist/jquery.min.js}"
 @表示static路径
 假设html在templates目录下,
 <link href="../static/blog/..."
th:href 与 href 的区别
 href始终从端口开始作为根路径,如8080/channel/page/add
 th:href会寻找项目路径作为根路径,如8080/dx/channel/page/add
 4.定义组件及使用
 th:fragment="header(title,keywords)"  header是组件名称,后面是传递参数
使用方式: html页面::组件名称(参数)
 th:replace="blog/yummy-jekyll/header::header('首页','My Blog')"  



















