Thymeleaf 教程

常见 th 属性

Thymeleaf 提供了大量的 th 属性,这些属性可以直接在 HTML 标签中使用,其中常用 th 属性及其示例如下:

th:id

替换 HTML 的 id 属性。例如:将“html-id”替换成“thymeleaf-id”

<input  id="html-id"  th:id="thymeleaf-id"  />

th:text

文本替换,转义特殊字符。例如:将“hello”字符串替换成“hello,hxstrive.com”

<h1 th:text="hello,hxstrive.com">hello</h1>

th:utext

文本替换,不转义特殊字符。例如:

<div th:utext="'<h1>欢迎来到人人编程网</h1>'">欢迎您</div>

th:object

在父标签选择对象,子标签使用 *{…} 选择表达式选取值。没有选择对象,那子标签使用选择表达式和 ${…} 变量表达式是一样的效果。即使选择了对象,子标签仍然可以使用变量表达式。例如:

<div th:object="${user}">
    <p th:text="*{id}"></p>
    <p th:text="*{username}"></p>
    <p th:text="${user.email}"></p>
</div>

th:value

替换 value 属性,例如:

<input th:value = "${user.username}" value="默认值"/>

th:with

局部变量赋值运算,例如:

<div th:with="isEvens = ${prodStat.count}%2 == 0"  th:text="${isEvens}"></div>

th:style

设置样式,例如:

<div th:style="'color:#F00; font-weight:bold'">人人编程网</div>

th:onclick

点击事件,例如:

<td th:onclick = "'getInfo()'"></td>

th:each

遍历,支持 Iterable、Map、数组等。例如:

<table>
    <tr th:each="m:${session.map}">
        <td th:text="${m.getKey()}"></td>
        <td th:text="${m.getValue()}"></td>
    </tr>
</table>

th:if

根据条件判断是否需要展示此标签,例如:

<a th:if ="${userId == collect.userId}">

th:unless

和 th:if 判断相反,满足条件时不显示,例如:

<div th:unless="${m.getKey()=='name'}" ></div>

th:switch

与 Java 的 switch case语句类似。通常与 th:case 配合使用,根据不同的条件展示不同的内容,例如:

<div th:switch="${type}">
    <span th:case="1">人人编程网</span>
    <span th:case="2">www.hxstrive.com</span>
</div>

th:fragment

模板布局,类似 JSP 的 tag,用来定义一段被引用或包含的模板片段,例如:

<footer th:fragment="footer">插入的内容</footer>

th:insert

布局标签,将使用 th:fragment 属性指定的模板片段(包含标签)插入到当前标签中。例如:

<div th:insert="commons/bar::footer"></div>

th:replace

布局标签,使用 th:fragment 属性指定的模板片段(包含标签)替换当前整个标签。例如:

<div th:replace="commons/bar::footer"></div>

th:selected

设置 select 选择框选中,例如:

<select>
    <option>---</option>
    <option th:selected="${name=='a'}">人人编程网</option>
    <option th:selected="${name=='b'}">www.hxstrive.com</option>
</select>

th:src

替换 HTML 中的 src 属性,例如:

<img  th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" />

th:inline

内联属性,该属性有 text、none、javascript 三种取值。在 <script> 标签中使用时,js 代码中可以获取到后台传递页面的对象。例如:

<script type="text/javascript" th:inline="javascript">
    var name = /*[[${name}]]*/ 'bianchengbang';
    alert(name)
</script>

th:action

替换表单提交地址,例如:

<form th:action="@{/user/login}" th:method="post"></form>
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号