Springboot(五)——thymeleaf模板引擎

thymeleaf模板引擎

thymeleaf模板引擎

一、导入thymeleaf依赖或者在创建项目的时候勾选thymeleaf模板引擎

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

二、根据源码,我们使用thymeleaf模板的时候,需要将html放在templates目录下

在templates目录下的所有页面,只能通过controller跳转!
并且需要模板引擎的支持!thymeleaf

private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";

thymeleaf使用

一、编写controller

@RequestMapping("/test")
public String test(Model model){
    model.addAttribute("msg","hello,springboot");
    return "test";
}

二、在templates目录下新建test.html

<!DOCTYPE html>
<!--注:这里一定要引入头文件-->
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text  取出的值被转义成text-->
<div th:text="${msg}"></div>
</body>
</html>

三、运行测试

image

thymeleaf语法

一、controller编写

@RequestMapping("/test")
public String test(Model model){
    model.addAttribute("msg","<h1>hello,springboot</h1>");
    model.addAttribute("users", Arrays.asList("zhangsan","lisi"));
    return "test";
}

二、html修改

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text  标注这个值是test-->
<div th:text="${msg}"></div>
<!--不转义-->
<div th:utext="${msg}"></div>
<hr>
<!--遍历集合-->
<h3 th:each=" user:${users}" th:text="${user}"></h3>
<!--遍历集合方式二:没有提示-->
<h3 th:each=" user:${users}" >[[${user}]]</h3>
<hr>
</body>
</html>

三、运行测试结果

image

thymeleaf语法糖

基础语法

  • 普通变量:${}
  • 国际化消息:#{}
  • url链接@{}
  • 判断表达式~{}
  • 文本:'test'(单引号)

三元条件运算符

  • if-then:(if)?(then)
  • if-then-else:(if)?(then):(else)
  • Defult:(value)?:(defultvalue)

分割表达式:_

posted @ 2021-06-28 16:13  转身刹那的潇洒  阅读(153)  评论(0编辑  收藏  举报