Thymeleaf的属性之遍历迭代、条件判断 ╰+攻爆jí腚メ 2022-05-26 04:48 178阅读 0赞 之前一直用的是freemaker,现在公司的问题回答模板使用Thymeleaf来实现,那么就来记录一下Thymeleaf的一些循环的语法 ###### 普通循环 ###### <tr th:each="prod : ${prods}"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> </tr> 1.prod局部变量只在被其包含的标签和子标签中可用; 2.迭代的对象可以是 java.util.List,java.util.Map,数组等; ###### 状态变量 ###### <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> </tr> -------------------- iterStat称作状态变量,属性有: index: 当前迭代对象的index(从0开始计算) count: 当前迭代对象的index(从1开始计算) size: 被迭代对象的大小 current:当前迭代变量 even/odd: 布尔值,当前循环是否是偶数/奇数(从0开始计算) first: 布尔值,当前循环是否是第一个 last: 布尔值,当前循环是否是最后一个 示例: <ol> <li>List循环: <table border="1"> <tr> <th>用户名</th> <th>邮箱</th> <th>管理员</th> <th>状态变量:index</th> <th>状态变量:count</th> <th>状态变量:size</th> <th>状态变量:current.userName</th> <th>状态变量:even</th> <th>状态变量:odd</th> <th>状态变量:first</th> <th>状态变量:last</th> </tr> <tr th:each="user,userStat : ${list}"> <td th:text="${user.userName}">Onions</td> <td th:text="${user.email}">test@test.com.cn</td> <td th:text="${user.isAdmin}">yes</td> <th th:text="${userStat.index}">状态变量:index</th> <th th:text="${userStat.count}">状态变量:count</th> <th th:text="${userStat.size}">状态变量:size</th> <th th:text="${userStat.current.userName}">状态变量:current</th> <th th:text="${userStat.even}">状态变量:even****</th> <th th:text="${userStat.odd}">状态变量:odd</th> <th th:text="${userStat.first}">状态变量:first</th> <th th:text="${userStat.last}">状态变量:last</th> </tr> </table> </li> <li>Map循环: <div th:each="mapS:${map}"> <div th:text="${mapS}"></div> </div> </li> <li>数组循环: <div th:each="arrayS:${arrays}"> <div th:text="${arrayS}"></div> </div> </li> </ol> -------------------- ###### 条件判断 ###### th:if属性求Bool值,只有true的时候其所在的标签及该标签中的内容才会被渲染到输出结果中 <a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a> -------------------- th:if=“expression”对expression求值有下述规则 * 值不为null,下列表达式都求值为true * boolean值true本身 * 非0数 * 非’0’字符 * “false”, “off”, “no”之外的字符串 * boolean,number,character,string之外的任意其他对象 值为null被认为是false -------------------- th:unless是th:if的一个相反操作,上面的例子可以改写为 <a href="comments.html" th:href="@{/comments(prodId=${prod.id})}" th:unless="${#lists.isEmpty(prod.comments)}">view</a> th:switch/th:case -------------------- <div th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> <p th:case="*">User is some other thing</p> </div> 一旦某个case求值为true,剩余的case则都当做false,“\*”指明默认case。
还没有评论,来说两句吧...