thymeleaf 模板参数设置
程序员文章站
2022-06-22 19:18:21
thymeleaf模板参数...
thymeleaf 模板参数
*********************
模板参数
定义模板,设置参数
<div th:fragment="frag (onevar,twovar)">
<p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>
引入模板,传递参数
<div th:replace="::frag (${value1},${value2})">...</div> //引入结果与参数顺序有关
<div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div> //引入结果与参数顺序无关
注意:如果定义模板时没有设置参数,引用模板时传递参数
<div th:fragment="frag">
...
</div>
**********
引入模板
<div th:replace="::frag (onevar=${value1},twovar=${value2})"> //与下等同
<div th:replace="::frag" th:with="onevar=${value1},twovar=${value2}">
仍可正常引入,相当于定义了局部变量
th:assert:参数验证,多参验证逗号间隔
<div th:assert="${onevar},(${twovar} != 43)">...</div>
<header th:fragment="contentheader(title)" th:assert="${!#strings.isEmpty(title)}">...</header>
只要检验到返回false,则抛出异常
*********************
示例
commons2.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:align="center" style="color: coral" th:fragment="fun(var,var2)">
<strong>
var ==> <span th:text="${var}"></span><br>
var2 ==> <span th:text="${var2}?:'null'"></span>
</strong>
</div>
<div th:align="center" style="color: coral" th:fragment="fun2">
<strong>
<span th:text="'hello 瓜田李下'"></span>
</strong>
</div>
</body>
</html>
index2.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:align="center">
<strong>
<span style="color: purple" th:text="'commons fun(var,var2)'"></span>
</strong>
<div th:replace="commons2 :: fun('瓜田李下','海贼王')"></div>
<div th:replace="commons2 :: fun(var2='海贼王',var='瓜田李下')"></div>
<div th:replace="commons2 :: fun('海贼王',null)"></div>
</div><br>
<div th:align="center">
<strong>
<span style="color: purple" th:text="'commons fun2'"></span>
</strong>
<div th:replace="commons2 :: fun2"></div>
<div th:replace="commons2 :: fun2(var='海贼王',var2='瓜田李下')"></div>
</div>
</body>
</html>
说明:
fun有参数,引入片段时需要传递两个参数(参数可为null),commons2 ::fun(‘海贼王’)会报错
fun2无参数,如果引入的时候传递参数,需要设置参数的名称(名称可为任意值,相当于定义了局部变量)
*********************
使用测试
本文地址:https://blog.csdn.net/weixin_43931625/article/details/107907296
上一篇: 口头禅
下一篇: 我们每个人都漂亮得像贵妃