# 3.模板引擎Thymeleaf

## 模板引擎Thymeleaf

①创建新项目，选择thymeleaf模板引擎和devTools开发工具和web依赖

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIf5fUmIbt70iK6n%2F3.1.png?generation=1558862972980521\&alt=media)

②新建WebController文件和index模板文件

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIf7xIdu8Pf-G6_m%2F3.2.png?generation=1558862973137703\&alt=media)

WebController.java

```java
package com.shuju.example.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/web")
public class WebController {

    @RequestMapping(value = "index")
    public String index(ModelMap map) {
        map.put("title", "thymeleaf hello word");
        return "index";
    }

}
```

src/main/resources/templates/index.html

```markup
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1  th:text="${title}"></h1>
</body>
</html>
```

③启动测试，title已进行了解析

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTIf9_VAGlC-r2KFf%2F3.3.png?generation=1558862972962219\&alt=media)

## 其他

### 手动直接引入依赖

修改pom.xml,添加如依赖

```markup
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```

### 资料

[Thymeleaf 基本用法总结](https://www.cnblogs.com/topwill/p/7434955.html)

```
1:引入Thymeleaf
  1.1：<html xmlns:th="http://www.thymeleaf.org">
        th:
  1.2:@{}
2:数据的访问
    ${}
    th:text="${Person.name}"
3：循环
    th:each="person:${people}"
4:条件判断；
${not#lists.isEmpty(people)}
5:数据输出
<script th:inline="javascript">
 var single=[[${singlePerson}]]
<script>
```

[springboot(四)：thymeleaf使用详解](https://blog.csdn.net/ityouknow/article/details/52441288)
