Thymeleaf 3.0教程:17 分离模板逻辑(一)
17.1 分离逻辑:概念
到目前为止,我们以通常的方式完成了杂货店模板的工作,逻辑以属性的形式插入到模板中。
但是Thymeleaf也允许我们将模板标记与其逻辑完全分离,允许在超文本标记语言和可扩展标记语言模板模式下创建完全无逻辑的标记模板。
主要思想是模板逻辑将在一个单独的逻辑文件中定义(更确切地说是一个逻辑资源,因为它不需要是一个文件)。默认情况下,该逻辑资源将是与模板文件位于同一位置(例如文件夹)的附加文件,具有相同的名称,但扩展名为.th.xml:
/templates +->/home.html +->/home.th.xml
所以home.html文件可以完全没有逻辑。可能是这样的:
<!DOCTYPE html> <html> <body> <table id="usersTable"> <tr> <td class="username">Jeremy Grapefruit</td> <td class="usertype">Normal User</td> </tr> <tr> <td class="username">Alice Watermelon</td> <td class="usertype">Administrator</td> </tr> </table> </body> </html>
绝对没有Thymeleaf代码。这是一个模板文件,没有Thymeleaf或模板知识的设计师可以创建、编辑和/或理解。或者是某个没有Thymeleaf挂钩的外部系统提供的一段超文本标记语言。
现在,让我们通过创建额外的home.th.xml文件,将home.th.xml模板转换为Thymeleaf模板,如下所示:
<?xml version="1.0"?> <thlogic> <attr sel="#usersTable" th:remove="all-but-first"> <attr sel="/tr[0]" th:each="user : ${users}"> <attr sel="td.username" th:text="${user.name}" /> <attr sel="td.usertype" th:text="#{|user.type.${user.type}|}" /> </attr> </attr> </thlogic>
在这里,我们可以看到一个逻辑块中有很多<attr>标签。这些<attr>标签通过它们的sel属性在原始模板的节点上执行属性注入,sel属性包含Thymeleaf标记选择器(实际上是AttoParser标记选择器)。
还要注意<attr>标签可以嵌套,这样它们的选择器就会被附加。例如,上面的sel="/tr[0]"将作为sel="#usersTable/tr[0]"处理。用户名<td>的选择器将被处理为 sel="#usersTable/tr[0]//td.username".。
还要注意<attr>标签可以嵌套,这样它们的选择器就会被附加。例如,上面的sel="/tr[0]"将被处理为sel = " #用户稳定/tr[0]"。用户名< td >的选择器将被处理为sel = " # user stable/tr[0]//TD . username "。
因此,一旦合并,上面看到的两个文件将与:
<!DOCTYPE html> <html> <body> <table id="usersTable" th:remove="all-but-first"> <tr th:each="user : ${users}"> <td class="username" th:text="${user.name}">Jeremy Grapefruit</td> <td class="usertype" th:text="#{|user.type.${user.type}|}">Normal User</td> </tr> <tr> <td class="username">Alice Watermelon</td> <td class="usertype">Administrator</td> </tr> </table> </body> </html>
这看起来更熟悉,而且确实没有创建两个单独的文件那么冗长。但是解耦模板的优势在于,我们可以让我们的模板完全独立于Thymeleaf,因此从设计的角度来看具有更好的可维护性。
当然,设计者或开发人员之间仍然需要一些约定:例如,用户<table>将需要一个id = " usersTable ",但是在许多情况下,纯HTML模板将是设计和开发团队之间更好的交流工具。