Thymeleaf的简单介绍与使用
thymeleaf:通过特定的语法html的标记作渲染
修改pom.xml,添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
变量输出与字符串操作
- th:text 在页面中输出值
- th:value 将一个值放入input标签的value中
- ${#strings.isEmpty(key)} 判断字符串是否为空,为空返回true,否则返回false
- thymeleaf内置对象 : strings 调用前要加#
- ${#string.contains(msg,”a”)} 判断字符串是否包含指定的子串
- ${#strings.startsWith(msg,”a”) 判断字符串是否以指定子串开头
- ${#strings.endsWith(msg,”a”) 判断字符串是否以指定子串结尾
- ${#strings.length(msg)} 返回字符串的长度
- ${#strings.indexof(msg,’h’)} 查找子串的位置,并返回下标,没有则返回-1
- ${#strings.substring(msg,1,[2])} 截取子串
- ${#strings.toUpperCase(msg)} 转大写
- ${#strings.toLowerCase(msg)} 转小写
日期格式化处理
- ${#dates.format(key)} 格式化日期,以浏览器默认语言为格式化标准
- ${#dates.format(key,’yy/MM/dd’)} 根据自定义格式格式化日期
- ${#dates.year(key)}
- ${dates.month(key)}
- ${#dates.day(key)}
条件判断 th:if
<span th:if="${msg}=='男'">男</span>
<span th:if="${msg} == '女'">女</span>
th:switch=” “ th:case=” “
<div th:switch="${msg}">
<span th:case="男">男 </span>
<span th:case="女">女</span>
</div>
迭代遍历th:each=” u : ${list}”
<table>
<tr>
<th>ID</th><th>name</th><th>pwd</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.password}"></td>
</tr>
</table>
状态变量属性
<table>
<tr th:each="user,var : ${users}">
<td th:text="${user.name}"></td>
<td th:text="${var.index}"></td> <!-- 当前迭代器的索引,从0开始 -->
<td th:text="${var.count}"></td> <!-- 当前迭代器的计数,从1开始 -->
<td th:text="${var.size}"></td> <!-- 被迭代对象的长度 -->
<td th:text="${var.even}"></td> <!-- 当前循环是否是偶数 从0开始 -->
<td th:text="${var.odd}"></td> <!-- 当前循环是否是奇数 -->
<td th:text="${var.first}"></td> <!-- 当前循环是否是第一条 -->
<td th:text="${var.last}"></td> <!-- 当前循环是否是最后一条 -->
</tr>
</table>
遍历map
<table>
<tr>
<th>ID</th><th>name</th><th>pwd</th>
</tr>
<tr th:each="entry:${map}">
<td th:text="${entry.value.id}"></td>
<td th:text="${entry.value.name}"></td>
<td th:text="${entry.value.password}"></td>
</tr>
</table>
域对象中取值
<h1 th:text="${#httpServletRequest.getAttribute('req')}"></h1>
<h1 th:text="${session.sess}"></h1>
<h1 th:text="${application.app}"></h1>
<h1 th:text="${req}"></h1>
url类型
<a th:href="@{http://www.baidu.com}">绝对路径</a><br/>
<a th:href="@{/show}">相对路径(相对项目的根)</a><br/>
<a th:href="@{~/project2/resource}">相对服务器的根</a>
<a th:href="@{/show(id=1,name='zhangsan')}">相对路径传参</a>
<a th:href="@{/show/1/zhangsan}">restful风格传参</a>