Thymeleaf 官网英文文档:https://www.thymeleaf.org/
平时工作有接触到Thymeleaf 框架,因为网上只有英文的文档,所以自己希望记录一些常用的写法,希望对大家也有用。
- 常用的th标签
有非常多的标签,这里只列出最常用的几个,由于一个标签内可以包含多个th:x属性,其生效的优先级顺序为:
include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src,etc,text/utext,fragment,remove。
关键字 | 功能介绍 案例 |
---|---|
th:id | 替换id <input th:id=”‘xxx’ + ${collect.id}”/> |
th:text | 文本替换 <span class=”name” th:text=”${nickName}”></span> |
th:utext | 支持html的文本替换 <p th:utext=”${htmlcontent}”>conten</p> |
th:object | 替换对象 <div th:object=”${session.user}”> |
th:value | 属性赋值 <input th:value=”${user.name}” /> |
th:onclick | 点击事件 < div th:onclick=”‘getCollect()'”> |
th:each | 属性赋值 <tr th:each=”user,userStat:${users}”> |
th:if | 判断条件,true <a th:if=”${userId == collect.userId}” > |
th:unless | 和th:if判断相反 ,false <a th:unless=${session.user != null}>Login</a> |
th:include | 布局标签,替换内容到引入的文件 <head th:include=”layout :: htmlhead” th:with=”title=’xx'”></head> |
th:with | 变量赋值运算 <div th:with=”isEven=${prodStat.count}%2==0″></div> |
th:replace | 布局标签,替换整个标签到引入的文件 <div th:replace=”fragments/header :: title”></div> |
th:src | 图片类地址引入 <img class=”img-responsive” th:src=”@{/img/logo.png}” /> |
th:remove | 删除某个属性 <tr th:remove=”all”> 1.all:删除包含标签和所有的孩子。 |
- URL表达式
URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL重写,写法:@{……}。
@{/order/list}
URL还可以设置参数:@{/order/details(id=${orderId})}
相对路径:@{…/documents/report}
让我们看这些表达式:
//链接路径
<a th:href="@{/html/proposal/card}