thymeleaf语法及使用

模板引擎

简介:模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。
模板引擎的思想:
在这里插入图片描述
Thymeleaf就是SpringBoot给我们推荐的一种模板引擎!

Thymeleaf模板引擎

1.使用Thymeleaf之前的步骤

  1. Thymeleaf 官网:https://www.thymeleaf.org/
  2. springboot项目直接引入依赖:
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.非springboot项目直接引入依赖:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4</version>
</dependency>

4.在thymeleaf的配置类ThymeleafProperties中我们可以发现:thymeleaf配置的默认前缀为:“classpath:/templates/”,默认后缀为:".html",只要把html页面放在这个路径下,

thymeleaf就可以帮我们自动渲染。

public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
...
}

如图为用idea创建的springboot的项目结构:将html页面放在resources/templates中即可。
在这里插入图片描述

2.Thymeleaf语法简单使用(th:text, th:utext, th:each)

编写一个controller实现跳转到一个html页面,通过Model对象携带数据

@Controller
public class HelloController {

    @RequestMapping("/success")
    public String success(Model model){
        //存入数据
        model.addAttribute("msg","<h1>Hello</h1>");
        model.addAttribute("users", Arrays.asList("小红", "小米","小白"));
        //classpath:/templates/success.html
        return "success";
    }
}

success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>success</h1>

    <!--Thymeleaf语法:th:text就是将div中的内容设置为它指定的值-->

    <div th:text="${msg}">你好</div>
    <!--utext:会解析html,显示相应的效果-->
    <div th:utext="${msg}">你好</div>
    <!--each:遍历-->
    <h3 th:each="user:${users}" th:text="${user}"></h3>

</body>
</html>

通过http://localhost:8080/success路径访问到success.html页面,同时成功显示数据:在这里插入图片描述

3.Thymeleaf基本语法(属性和表达式)

Thymeleaf标准表达式

  1. 变量表达式:${ }:用于前端获取后端传递的变量值

  2. 选择表达式:*{ }:用于绑定一个对象的属性

  3. URL链接表达式:@{ }:用于链接

  4. 条件表达式:三目运算符(表达式 ?值(then):值(else))

Thymeleaf属性标签:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 26 · 访问量 7160

猜你喜欢

转载自blog.csdn.net/qq_42804736/article/details/104347171