天天看点

thymeleaf - 常用标签

官方文档:

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

thymeleaf 标签用法

引入DTD:
<html xmlns:th="http://www.thymeleaf.org">...</html>
           
note:

th 标签会覆盖html标签中的内容,包括th标签引用的类,也会覆盖原来的类

_______________________________________________________

懒得写太多,引用下别人写的一些:https://blog.csdn.net/hepei120/article/details/80319422?utm_source=blogxgwz1

1) navigation文件中创建一个叫nav的片段 (共通部分可写在这儿)

<div th:fragment="nav">...</div>
           

在另外一个文件中引用navigation文件中定义的nav片段

<div th:insert="~{navigation :: nav}"></div>
           

2) 格式化时间(例如格式化 user.createTime)

<span th:text="${#dates.format(user.createTime,'yyyy-MM-dd HH:MM')}"></span>
           

3) 遍历 (例如遍历questions)

<div class="media" th:each="question : ${questions}">...</div>
           

4) 图片链接

<img th:src="${user.avatarUrl}">
           

5) a标签链接 - 拼接字符串

<!--两种方式都可以-->
<a th:href="@{'/question/{id}(id=${question.id})'}" target="_blank" rel="external nofollow"  th:text="${question.title}"></a>
<a th:href="@{'/question/'+${question.id}}" target="_blank" rel="external nofollow"  th:text="${question.title}"></a>
           

6) if 判断,为true才会显示 li 标签的内容

<li th:if="${user.name != null}">...<li>
           

7) 添加类,用了三目运算符

<li th:class="${username == name} ? 'active':''"></li>
           

8) th:value 在 input 输入框内,th:text 在input输入框外

<input type="hidden" name="id" th:value="${id}">
           

9) th:switch 、th:case

<div th:switch="${user.name}">
    <p th:case="xiaoMing">我叫小明</p>
    <p th:case="${otherUser.name}">我是其他用户的名字</p>
</div>
           

10) th:action

<form th:action="@{user/login}" method="post"></form>
           

11) th:selected 用于选择框设置选中值。通常和th:each一起使用。

<select>
    <option th:selected="${user.name} == ${otherUser.name}"></option> 若相等就默认选中此<option></option>
</select>
           

12) th:object 用于表单数据对象绑定,后台controller中参数保持一致,和选择(星号)表达式。

<form th:object="${user}">
    <input th:value="*{name}"/>      //*号代替了${user}
</form>
public ModelAndView addUser(@RequestParam(value = "user") User user,ModelMap model){}
           

13) th:attr 用于设置任意属性

<input th:attr="value=${user.name}"/> 设置单个属性。
<input th:attr="value=${user.username},name=username"/> 设置多个属性之间用逗号隔开。
           

14) 是否包含(不分大小写)

<span th:if="${#strings.containsIgnoreCase(name,'xyz')}">时候包含xyz</span> 
           

15) str截取0-10位,后面的全部用…这个点代替,注意,最小是3位

${#strings.abbreviate(str,10)}
           

如若有不正确的地方,还望指出,thank you!

__________________________________________________

永远相信美好的事情即将发生