这次我们来学习Thymeleaf特有的注释模块。
Standard HTML/SML comments
<!-- … --> 注释可以用在 Thymeleaf 模板中的任何地方,但是不会被 Thymeleaf 处理,它会随着必要的代码一字不差的复制到网页的源代码页。
...
<h1 th:text="#{hone.welcome}" th:fragment="copy">Welcome to our grocery store!</h1>
<div>
<p>en_Name: <span th:text="*{user.enname}">Sebastian</span></p>
<p>cn_Name: <span th:text="${user.cnname}">塞巴斯蒂安</span></p>
</div>
<!-- 哎呀暴露了!本页面是地下赌场的隐藏入口!-->
<div th:insert="menu :: menu-copy(~{::title})" th:assert="1,2"></div>
...
👮♂️:你再说,我在听
🏃♂️:额,先撤了
咳~开玩笑的,我们继续学习
Thymeleaf parser-level comment blocks
<!--/* This code will be removed at Thymeleaf parsing time! */--> 注释会在 Thymeleaf 解析它的时候将它从网页源码页中移出。
...
<h1 th:text="#{hone.welcome}" th:fragment="copy">Welcome to our grocery store!</h1>
<div>
<p>en_Name: <span th:text="*{user.enname}">Sebastian</span></p>
<p>cn_Name: <span th:text="${user.cnname}">塞巴斯蒂安</span></p>
</div>
<!--/* 哎呀暴露了!本页面是地下赌场的隐藏入口!*/-->
<div th:insert="menu :: menu-copy(~{::title})" th:assert="1,2"></div>
...
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-e6wif9Mc-1659251707129)(/images/Thymeleaf/网页源码移.png)]
🦸♂️:嘿~哪有啊
👮♂️:刚那人呢
<!--/* and */--> 注释会在 Thymeleaf 解析它的时候把它内部所有的字符移除:
<!--/*-->
<div>you can see me only before Thymeleaf processes me! </div>
<!--*/-->
甚至可以在里面放代码,因为它会在 Thymeleaf 解析它时把它移除。
th:remove 属性也可以移除代码块 , 根据属性的值的不同有不同的效果:
· all : 移除本标签和所有的子标签。
· body : 只移除所有的子标签。
· tag : 只移除本标签。
· all-but-first : 只移除所有的子标签(除了第一个)。
· none : 什么都不做。
对于 none 值,there is a example:
<a href="/something" th:remove="${condition}? tag : none">Link text not to be removed</a>
下面的例子运行效果与上述例子一样:
<a href="/something" th:remove="${condition}? tag">Link text not to be removed</a>
因为 th:remove 属性会把 null 等同于 none 。
扯远了,我们继续学习注释。
Thymeleaf prototype-only comment blocks
例如
<span>hello!</span>
<!--/*/
<div th:text="${...}">
...
</div>
/*/-->
<span>goodbye!</span>
Thymeleaf 在解析它时只会把 <!--/*/ 和 /*/--> 移除,相当于:
<span>hello!</span>
<div th:text="${...}">
...
</div>
<span>goodbye!</span>
这种注释只会在开发时被程序员看到,但 Thymeleaf 处理时会自动将它忽略,执行其内部的代码。当作为标准 HTML 页面打开时,注释仍然存在。
Synthetic th:block tag
Thymeleaf 的唯一一个包含在标准语法中的元素处理器是 th:block 。
它和 prototype-only comment blocks 一起使用会非常简洁:
<table>
<!--/*/ <th:block th:each="user : ${users}"> /*/-->
<tr>
<td th:text="${user.login}">...</td>
<td th:text="${user.name}">...</td>
</tr>
<tr>
<td colspan="2" th:text="${user.address}">...</td>
</tr>
<!--/*/ </th:block> /*/-->
</table>
程序猿可以在 <th:block> 标签内定义任何自己想要的属性,剩下的交给 Thymeleaf ,当 <th:block> 被执行时,Thymeleaf 会移除 block 而留下它的 内容,就像被注释掉一样,更加简洁。
— 【参考资料 —— Thymeleaf文档20181029 - 29 October 2018】
已同步更新至个人博客:田超杰的个人网站-一个传播计算机知识和人生哲理的博客