Thymeleaf常用語法:條件判斷 if、switch case


if語句
條件判斷使用th:if,它會判斷表達式是否成立,表達式的結果支持boolean、number、character、String及其他類型。
滿足下面情況,if語句成立:
(1) 表達式的結果是數字且不是0
(2) 表達式的結果是字符串且不是false、off、no、0
(3) 表達式的結果是其他數據類型
switch case語句
(1) 類似Java的switch case語句:th:switch、th:case
(2) 使用th:case="*"來表示默認值
(3) 如果第一個th:case結果為true,則其它所有的th:case會被設置為false,即使它們的結果也是true

開發環境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

新建一個名稱為demo的Spring Boot項目。

1、pom.xml
加入Thymeleaf依賴

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

2、src/main/java/com/example/demo/TestController.java

package com.example.demo;

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

import java.util.ArrayList;
import java.util.List;

@Controller
public class TestController {
    @RequestMapping("/")
    public String test(Model model){
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        model.addAttribute("list", list);
        model.addAttribute("flag", true);
        model.addAttribute("gender", 1);
        return "test";
    }
}

3、src/main/resources/templates/test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h4>一、條件判斷</h4>
     [1]<div th:text="true" th:if="${flag}"></div>
     [2]<div th:text="'數字,非0'" th:if="10"></div>
     [3]<div th:text="'字符串,非false、off、no'" th:if="'a'"></div>
     [4]<div th:text="其他數據類型" th:if="${list}"></div>
     [5]<div th:text="字符串0" th:if="'0'"></div>
     [6]<div th:text="數字0" th:if="0"></div>
     [7]<div th:text="false" th:if="'false'"></div>
     [8]<div th:text="off" th:if="'off'"></div>
     [9]<div th:text="no" th:if="'no'"></div>
<h4>二、switch case</h4>
    <select th:switch="${gender}">
        <option th:case="1"></option>
        <option th:case="0"></option>
        <option th:case="*">其他</option>
    </select>

    <select th:switch="2">
        <option th:case="1"></option>
        <option th:case="0"></option>
        <option th:case="*">其他</option>
    </select>

</body>
</html>

瀏覽器訪問:http://localhost:8080
右鍵查看網頁源代碼,生成的HTML源碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h4>一、條件判斷</h4>
     [1]<div>true</div>
     [2]<div>數字,非0</div>
     [3]<div>字符串,非false、off、no</div>
     [4]<div>其他數據類型</div>
     [5]<div>字符串0</div>
     [6]
     [7]
     [8]
     [9]
<h4>二、switch case</h4>
    <select>
        <option></option>
        
        
    </select>

    <select>
        
        
        <option>其他</option>
    </select>

</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM