Thymeleaf 3.0教程:11 注释和块
11.1. 标准的HTML/XML注释
标准的HTML/XML注释<!-- ... -->可以在Thymeleaf模板中的任何地方使用。Thymeleaf不会处理这些评论中的任何内容,并将逐字复制到结果中:
<!-- User info follows --> <div th:text="${...}"> ... </div>
11.2. Thymeleaf解析器级注释块
解析器级别的注释块是在Thymeleaf解析模板时将从模板中简单移除的代码。它们看起来像这样:
<!--/* This code will be removed at Thymeleaf parsing time! */-->
Thymeleaf将清除<!--/* 和 */-->,因此这些注释块也可以用于在模板静态打开时显示代码,知道Thymeleaf处理它时会将其删除:
<!--/*--> <div> you can see me only before Thymeleaf processes me! </div> <!--*/-->
这对于具有大量<tr>的原型表可能非常方便,例如:
<table> <tr th:each="x : ${xs}"> ... </tr> <!--/*--> <tr> ... </tr> <tr> ... </tr> <!--*/--> </table>
11.3. Thymeleaf prototype-only评论块
Thymeleaf允许在模板静态打开时(即作为原型)将特殊注释块定义为注释,但在执行模板时被Thymeleaf视为正常标记。
<span>hello!</span> <!--/*/ <div th:text="${...}"> ... </div> /*/--> <span>goodbye!</span>
Thymeleaf的解析系统将简单地删除<!- /*/和/*/ ->标记,但不包括其内容,因此内容将被取消注释。所以当执行模板时,Thymeleaf实际上会看到这个:
<span>hello!</span> <div th:text="${...}"> ... </div> <span>goodbye!</span>
与解析器级注释块一样,这个特性与方言无关。
11.4. th:block标签
Thymeleaf唯一包含在标准方言中的元素处理器(不是属性)是th:block。
th:block仅仅是一个属性容器,它允许模板开发人员指定他们想要的任何属性。Thymeleaf将执行这些属性,然后简单地使块消失,而不是它的内容消失。
因此,例如,当创建迭代表时,每个元素需要一个以上的<tr>时,这可能会很有用:
<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>
与prototype-only注释块结合使用时尤其有用:
<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>
注意这个解决方案如何允许模板成为有效的HTML(不需要在<table>中添加禁止的<div>块),并且当在浏览器中作为原型静态打开时仍然可以工作!