SpringBoot中thymeleaf模板引擎常用知识点

1、拼接url

1
<img th:src="@{/img/research/{filename}(filename=${research.filename})}">
1
<a th:href="@{'https://'+${url.url}}" th:text="${url.urlName}"></a>

2、在js中获取项目的路径

1
2
3
<script th:inline="javascript">
var basePath = [[${#httpServletRequest.getScheme() + "://" + #httpServletRequest.getServerName() + ":" + #httpServletRequest.getServerPort() + #httpServletRequest.getContextPath()}]];
</script>

3、获取session、model中的值

1
2
3
4
<script th:inline="javascript">
var userid = [[${session.userid}]];
var model=[[${modelname}]]
</script>

3、将公共界面抽离出来

其中th:fragment=”header” 表示下面的代码是公共部分

1
2
3
<div style="min-width:500px;" th:fragment="header">
内容
</div>

在其他界面上引用,代码如下

1
<div th:replace="~{index :: header}"></d
1
2
3
4
5
6
7
元素导入:
<div th:insert="~{footer :: copy}"></div> 早行内写法中只能使用~{}
或者: <div th:insert="footer :: copy"></div> 其他的情况都可以使用这种简便的写法

相当于:
~{templatename : : fragmentname} 模板名::片段名
~{templatename : : selector} 模板名::选择器名接!

模板名就是html的路径,默认去templates文件夹下找,这个路径不用加.html,在配置文件中配置过了。

4、If和往Js函数中传递参数

如果confirmDelete()函数需要字符串id ,请尝试这个

1
th:onclick="'javascript:confirmDelete(\'' + ${company.id} + '\');'"

如果它需要一个数字ID

1
th:onclick="'javascript:confirmDelete(' + ${company.id} + ');'"

5、 转义和非转义的 html 文本

1
2
3
4
<h2>显示 转义和非转义的 html 文本</h2>
<p th:text="${htmlContent}" ></p>
<p th:utext="${htmlContent}" ></p>

6、显示对象以及对象属性

1
2
3
4
5
6
7
8
9
10
11
<div class="showing">
<h2>显示对象以及对象属性</h2>
<p th:text="${currentProduct}" ></p>
<p th:text="${currentProduct.name}" ></p>
<p th:text="${currentProduct.getName()}" ></p>
</div>
<div class="showing" th:object="${currentProduct}">
<h2>*{}方式显示属性</h2>
<p th:text="*{name}" ></p>
</div>

7、循环遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
List<Product> ps = new ArrayList<>();
ps.add(new Product(1,"product a", 50));
ps.add(new Product(2,"product b", 100));
ps.add(new Product(3,"product c", 150));
ps.add(new Product(4,"product d", 200));
ps.add(new Product(5,"product f", 200));
ps.add(new Product(6,"product g", 200));
m.addAttribute("ps", ps);
---------------------------------------------------
<tr th:each="p: ${ps}">
<td th:text="${p.id}"></td>
<td th:text="${p.name}"></td>
<td th:text="${p.price}"></td>
</tr>

8、结合select、input

1
2
3
4
<select size="3">
<option th:each="p:${ps}" th:value="${p.id}" th:selected="${p.id==currentProduct.id}" th:text="${p.name}" ></option>
</select>

1
2
<input name="product" type="radio" th:each="p:${ps}" th:value="${p.id}"  th:checked="${p.id==currentProduct.id}"     th:text="${p.name}"  />

9、格式化日期

1
2
3
4
5
6
7
直接输出日期 ${now}:
<p th:text="${now}"></p>
默认格式化 ${#dates.format(now)}:
<p th:text="${#dates.format(now)}"></p>
自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
<p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>

10、判断集合是否为空

1
2
th:if="${not #lists.isEmpty(集合名称)}">

 wechat
欢迎您扫一扫上面的微信公众号,订阅我的个人公众号!
坚持技术分享!