這里介紹thymeleaf的編程語法,本節(jié)主要包括如下內(nèi)容
下文演示以上語法的用法。
User
public class User { private String name; private boolean isAdmin; private String other; private int age; public User(String name, boolean isAdmin, String other, int age) { super(); this.name = name; this.isAdmin = isAdmin; this.other = other; this.age = age; } // set/get略}
ProgrammingCtl : control類
@Controller@RequestMapping("/programming")public class ProgrammingCtl { @RequestMapping("programming") public String iteration(ModelMap modeMap) { // Iteration List<User> userList = new ArrayList<User>(); userList.add(new User("son_1", true, "other_1", 11)); userList.add(new User("son_2", false, "other_2", 22)); userList.add(new User("son_3", true, "other_3", 33)); userList.add(new User("son_4", false, "other_4", 44)); modeMap.put("userList", userList); // ifelse User userIf = new User("admin", true, "other_if", 11); modeMap.put("user", userIf); return "programming/programming"; }}
本請求轉(zhuǎn)到頁面programming.html,
常用th:each用法:
<table border="2"> <thead> <tr> <th>name</th> <th>age</th> <th>isAdmin</th> </tr> </thead> <tbody> <!-- 常用的迭代 th:each 用法 --> <tr th:each="user : ${userList}"> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> <td th:text="${user.isAdmin}"></td> </tr> </tbody></table>
運行結(jié)果如下:
迭代的對象
本例子中迭代的對象是Java.util.List,除了List,還可以對以下對象進行迭代
獲取迭代的中間的狀態(tài),定義在iterStat中
在迭代過程中,可以獲取迭代的中間狀態(tài),詳細如下:
<table border="2"> <thead> <tr> <th>迭代索引</th> <th>元素所處的位置索引</th> <th>奇偶行</th> <th>name</th> <th>age</th> <th>isAdmin</th> </tr> </thead> <tbody> <!-- 獲取迭代的中間的狀態(tài),定義在iterStat中--> <tr th:each="user,iterStat : ${userList}"> <!-- index: 當前迭代的索引 --> <td th:text="${iterStat.index }"></td> <!-- first: 當前元素是第一個元素; last: 當前元素是最后個元素 --> <td th:text="${iterStat.first } ? '這是第一個元素':(${iterStat.last} ? '這是最后一個元素':'')" ></td> <!-- --> <td th:text="${iterStat.odd} ? 'odd' : 'even'" ></td> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> <td th:text="${user.isAdmin}"></td> </tr> </tbody></table>
運行結(jié)果如下:
演示如下功能
<!-- th:if:如果值是true,則打印<span>整個節(jié)點 --> <span th:if="${user.isAdmin}" th:text="${user.name} + '是管理員'"> </span><br /> <!-- th:unless: 和th:if是相反功能,如果值為false,則打印<span>整個節(jié)點 --> <span th:unless="not ${user.isAdmin}" th:text="${user.name} + '是管理員'"> </span><br />
輸出:
<span>admin是管理員</span><br /><span>admin是管理員</span><br />
th:if條件判斷
除了判斷boolean值外,thymeleaf還認為如下表達式為true:
演示如下功能
<!-- th:switch / th:case --><div th:switch="${user.name}"> <p th:case="'admin'">User is an administrator</p> <!-- *: case的默認的選項 --> <p th:case="*">User is some other thing</p></div>
輸出:
<div> <p>User is an administrator</p></div>
代碼詳細見Github