1. 程式人生 > >SpringBoot(十六):Thymeleaf使用

SpringBoot(十六):Thymeleaf使用

版權宣告

單純的廣告

個人部落格:https://aodeng.cc
微信公眾號:低調小熊貓
QQ群:756796932

簡介

簡介懶得打了.....(此處省略1萬字)

使用

這裡舉例使用thyme leaf的:賦值,拼接,if判斷,unless判斷,for 迴圈,URL,三目運算,switch 選擇(後面繼續新增)
頁面程式碼

<h3>賦值<h3>
    <h3 th:text="${hope1}">Thymeleaf test page</h3>
    <h3>拼接<h3>
    <span th:text="'thymeleaf 普通拼接:'+${hopeName}+'!'"></span>
    <span th:text="|thymeleaf 簡潔拼接:${hopeName}!|"></span>
    <h3>if判斷<h3>
    true: <a th:if="${hopes=='hopes'} " th:href="@{https://aodeng.cc}">if</a>
    false:<a th:if="${hopes=='hope'} " th:href="@{https://aodeng.cc}">if</a>
    <h3>unless判斷<h3>
    true: <a th:unless="${hopes!='hope'} " th:href="@{https://aodeng.cc}">unless</a>
    false:<a th:unless="${hopes=='hope'} " th:href="@{https://aodeng.cc}">unless</a>
    <h3>for 迴圈</h3>
    <table>
        <tr>
        <tr>
            id:
            name:
            password:
            sex:
            age:
            index:
        </tr>
        </tr>
        <tr th:each="user,iterStat:${userlist}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.password}"></td>
            <td th:text="${user.sex}"></td>
            <td th:text="${user.age}"></td>
            <td th:text="${iterStat.index}"></td>
        </tr>
    </table>
    terStat 稱作狀態變數,屬性有:
    index,當前迭代物件的 index(從 0 開始計算);
    count,當前迭代物件的 index(從 1 開始計算);
    size,被迭代物件的大小;
    current,當前迭代變數;
    even/odd,布林值,當前迴圈是否是偶數/奇數(從 0 開始計算);
    first,布林值,當前迴圈是否是第一個;
    last,布林值,當前迴圈是否是最後一個
    <h3>URL</h3>
        <a th:href="@{https://github.com/java-aodeng/{url}(url=${url})}">點選測試</a>
        上例中 URL 最後的(url=${url})表示將括號內的內容作為 URL 引數處理,該語法避免使用字串拼接,大大提高了可讀性
        <h3>三目運算</h3>
        <input th:value="${number gt 2 ? '值為1':'值不為1'}">
        gt:great than(大於)
        ge:great equal(大於等於)
        eq:equal(等於)
        lt:less than(小於)
        le:less equal(小於等於)
        ne:not equal(不等於)
     <h3>switch 選擇</h3>
        <div th:switch="${switch}">
            <p th:case="'0'">switch等於0</p>
            <p th:case="'1'">switch等於1</p>
            <p th:case="*">未知</p>
        </div>

後臺程式碼

@RequestMapping("/hope1")
    public String hope1(ModelMap map){
        map.addAttribute("hope1","Thymeleaf 賦值 start");
        map.addAttribute("hopeName","低調小熊貓很帥");
        map.addAttribute("hopes","hopes");
        List<User> userList=new ArrayList<>();
        User user=new User();
        user.setId(1);
        user.setName("admin");
        user.setPassword("123456");
        user.setSex("男");
        user.setAge(20);
        userList.add(user);
        map.addAttribute("userlist",userList);
        map.addAttribute("url","hope");
        map.addAttribute("number",1);
        map.addAttribute("switch","0");
        return "hope1";
    }

執行效果
file

原始碼

https://github.com/java-aodeng/hope
學習筆記,僅供參考