SpringBoot入门——Thymeleaf简单使用

本文只展示代码实现,具体参考此博客实现

举例使用Thymeleaf的:赋值,拼接,if判断,unless判断,for 循环,HTML文本替换

IndexController后台代码


@Controller
public class IndexController {
    /***
     * index页面
     */
    @RequestMapping("/Index")
    public ModelAndView Index(){
        /*for循环*/
        List<UserModel> users= new ArrayList<>();
        UserModel um=new UserModel();
            um.setAge("18");
            um.setName("Howie");
        UserModel um1=new UserModel();
            um1.setAge("20");
            um1.setName("Tang");
        users.add(um);
        users.add(um1);

        Map<String, Object> map=new HashMap<>();
            /*赋值*/
            map.put("description","Hello SpringBoot");
            /*拼接*/
            map.put("joint","Howie");
            /*for循环*/
            map.put("users", users);
            /*if unless判断*/
            map.put("test", "123");
            /*HTML文本替换*/
            map.put("HTML", "<h1>Hello</h1>");
        return new ModelAndView("index","result",map);
    }
}

index页面代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Hello Index</h1>

    <h2>赋值</h2>
    <p  th:text="${result.description}">description</p>

    <h2>拼接</h2>
    <span th:text="'Welcome,' + ${result.joint} + '!'"></span>

    <h2>for循环</h2>
    <span th:each="nn: ${result.users}">
        年龄:<span th:text="${nn.age}"></span>
        姓名:<span th:text="${nn.name}"></span>
        <br>
    </span>

    <h2>if判断</h2>
        <a href="www.baidu.com " th:if="${result.test =='123'}" ></i>百度</a>
        <a href="www.taobao.com " th:if="${result.test =='1234'}" ></i>淘宝</a>
        <br>

    <h2>unless判断</h2>
        <a href="www.baidu.com " th:Unless="${result.test =='123'}" ></i>百度</a>
        <a href="www.taobao.com " th:Unless="${result.test =='1234'}" ></i>淘宝</a>
        <br>

    <h2>HTML文本替换</h2>
    <span th:utext="${result.HTML}"></span>

</body>
</html>

Usermodel自定义

public class UserModel {
    public String name;
    public String age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }

运行页面效果

猜你喜欢

转载自blog.csdn.net/qq_41240108/article/details/84320821