1. 程式人生 > >SpringBoot入門——Thymeleaf簡單使用

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;
    }

執行頁面效果