11 简单的Thymeleaf语法

11.1 spring-boot环境准备

         重要依赖:

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

11.2 转发消息不转义

        就是如果一个字符串是<h1>一个标题</h1>这样,不转义就是一个字符串;如果转义了就是按html的语法输出一个标题。thymeleaf的语法是:只需要在标签中加入th:text属性,即为不转义写法。 

        controller类:传递name变量到hello.html页面。

package jiang.com.springbootstudy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/hello")
public class HelloWorldController {
    @RequestMapping("/test")
    public String hello(Model model){
        model.addAttribute("name","<h1>这是一个标题</h1>");
        return "hello";
    }
}

        static文件夹里的html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="${name}"></div>
</body>
</html>

        访问页面后的结果:

 11.3 转发消息转义

        转义是指当转发的字符串是按html规则写的,如<h1>这是标题</h1>,就会安装html的语法输出。thymeleaf中使用th:utext属性进行转义。

        controller代码与11.2一致。

         static文件夹里的html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:utext="${name}"></div>
</body>
</html>

          访问页面后的结果:

11.4 遍历数组

        controller类:使用Array.asList()将数组转为集合;

package jiang.com.springbootstudy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;

@Controller
@RequestMapping("/hello")
public class HelloWorldController {
    @RequestMapping("/test")
    public String hello(Model model){
        model.addAttribute("names", Arrays.asList("zhangsan", "lisi")); // Arrays.asList把数组转为集合
        return "hello";
    }
}

        html:先使用th:each = "name : ${names}" 遍历names,每次取出来的值赋给name变量;再使用th:text = "${name}",把name变量的值取出来:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:each= "names:${names}" th:text="${names}"></div>
</body>
</html>

        网址访问结果:

猜你喜欢

转载自blog.csdn.net/no996yes885/article/details/131879512