
8.4 Thymeleaf属性值讲解
8.4.1 Thymeleaf模板解读
在第一个Thymeleaf模板引擎整合案例中,读取动态数据并渲染的语句如下所示:

这是Thymeleaf模板引擎技术常见的语法规则,接下来详细分析这个知识点。
如图8-8所示,该模板文件语句中包含三部分内容。

图8-8 Thymeleaf模板语句
①html标签
②Thymeleaf模板引擎的th标签
③Thymeleaf表达式
前半部分p为HTML的标签,后半部分是Thymeleaf属性标签和表达式语法。th:text表示文本替换、${description}表示读取后台设置的description字段。该模板文件语句的作用就是动态地将p标签的内容替换为description字段的内容。
同时该语句也展示了Thymeleaf模板文件的编写规则。
①任意的Thymeleaf属性标签th:* 需要写在html标签中(th:block除外)
②Thymeleaf表达式写在Thymeleaf属性标签中
8.4.2 Thymeleaf属性值的设置
这部分将介绍一些关于Thymeleaf设置属性值的内容。
th:text对应HTML5语法中的text属性。除th:text属性以外,Thymeleaf模板引擎也提供了其他的标签属性来替换HTML5原生属性的值。标签属性节选如图8-9所示。

图8-9 Thymeleaf标签属性节选
其中th:background对应HTML5中的背景属性;th:class对应HTML5中的class属性;th:href对应HTML5中的链接地址属性;th:id和th:name分别对应HTML5中的id和name属性。
th:block比较特殊,它是Thymeleaf提供的唯一的一个Thymeleaf块级元素。其特殊性在于Thymeleaf模板引擎在处理<th:block>的时候会删掉其本身,而保留标签中的内容。
这里只列举了部分属性,完整内容可以查看thymeleaf-attributes。
8.4.3 修改属性值实践
在templates目录下新建attributes.html文件,笔者将演示使用Thymeleaf语法来修改其属性值。
attributes.html代码如下所示:

包含background、id、name、class等的html标签都设置了默认值,并在每个标签体中都添加了对应的th标签来读取动态数据。这里直接选择该文件,右键点击并选择Open in Browser查看页面效果,如图8-10所示。

图8-10 attributes.html页面默认显示效果
需要注意的是,当前页面是直接打开的,并没有通过Web服务器。此时,attributes.html页面能够直接正常访问且页面中的内容和元素的属性值都是默认值。
修改控制类代码,在ThymeleafController类中新增attributes()方法并将请求转发至该模板页面,代码如下所示:

在编码完成后,重启Spring Boot项目。在项目启动成功后,可以打开浏览器并访问如下地址:

得到的页面结果如图8-11所示。

图8-11 attributes.html模板引擎渲染后的显示效果
打开浏览器控制台查看该页面的节点,即图8-11所框选的内容。
由于th标签的存在,页面在通过Thymeleaf渲染后,与静态页面相比较,内容和元素属性已经动态切换了,原来的默认值都变成了attributes()方法中设置的值。
这部分内容可以结合笔者提供的源码进行理解,也可以使用其他常用的th标签来练习。