Skip to content

5.2 为特定属性赋值

看到这里,你可能会觉得像这样的代码:

html
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>

……写起来实在不够优雅。在一个属性的值里嵌套赋值表达式虽然能用,但如果每次设置属性都要这么写,模板的可读性会大打折扣。

Thymeleaf 也考虑到了这一点,这也是为什么 th:attr 在实际模板开发中很少被使用。通常情况下,你会使用另一类 th:* 属性——它们专门用于为特定的 HTML 标签属性赋值(而非像 th:attr 那样适配任意属性)。

比如,要设置 value 属性,直接使用 th:value 即可:

html
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>

这样看起来就清爽多了!我们再把表单标签里的 action 属性也改成这种写法:

html
<form action="subscribe.html" th:action="@{/subscribe}">

你还记得之前在 home.html 里用过的 th:href 吗?它其实就是同一类属性:

html
<li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>

这类“专用属性修饰符”的数量非常多,每一个都对应一个特定的 HTML5 属性,以下是完整列表:

th:abbrth:acceptth:accept-charset
th:accesskeyth:actionth:align
th:altth:archiveth:audio
th:autocompleteth:axisth:background
th:bgcolorth:borderth:cellpadding
th:cellspacingth:challengeth:charset
th:citeth:classth:classid
th:codebaseth:codetypeth:cols
th:colspanth:compactth:content
th:contenteditableth:contextmenuth:data
th:datetimeth:dirth:draggable
th:dropzoneth:enctypeth:for
th:formth:formactionth:formenctype
th:formmethodth:formtargetth:fragment
th:frameth:frameborderth:headers
th:heightth:highth:href
th:hreflangth:hspaceth:http-equiv
th:iconth:idth:inline
th:keytypeth:kindth:label
th:langth:listth:longdesc
th:lowth:manifestth:marginheight
th:marginwidthth:maxth:maxlength
th:mediath:methodth:min
th:nameth:onabortth:onafterprint
th:onbeforeprintth:onbeforeunloadth:onblur
th:oncanplayth:oncanplaythroughth:onchange
th:onclickth:oncontextmenuth:ondblclick
th:ondragth:ondragendth:ondragenter
th:ondragleaveth:ondragoverth:ondragstart
th:ondropth:ondurationchangeth:onemptied
th:onendedth:onerrorth:onfocus
th:onformchangeth:onforminputth:onhashchange
th:oninputth:oninvalidth:onkeydown
th:onkeypressth:onkeyupth:onload
th:onloadeddatath:onloadedmetadatath:onloadstart
th:onmessageth:onmousedownth:onmousemove
th:onmouseoutth:onmouseoverth:onmouseup
th:onmousewheelth:onofflineth:ononline
th:onpauseth:onplayth:onplaying
th:onpopstateth:onprogressth:onratechange
th:onreadystatechangeth:onredoth:onreset
th:onresizeth:onscrollth:onseeked
th:onseekingth:onselectth:onshow
th:onstalledth:onstorageth:onsubmit
th:onsuspendth:ontimeupdateth:onundo
th:onunloadth:onvolumechangeth:onwaiting
th:optimumth:patternth:placeholder
th:posterth:preloadth:radiogroup
th:relth:revth:rows
th:rowspanth:rulesth:sandbox
th:schemeth:scopeth:scrolling
th:sizeth:sizesth:span
th:spellcheckth:srcth:srclang
th:standbyth:startth:step
th:styleth:summaryth:tabindex
th:targetth:titleth:type
th:usemapth:valueth:valuetype
th:vspaceth:widthth:wrap
th:xmlbaseth:xmllangth:xmlspacev

总结

  1. th:attr 虽能设置任意属性,但写法冗余不优雅,仅在无专用修饰符时使用;
  2. Thymeleaf 为几乎所有 HTML5 原生属性提供了对应的 th:* 专用修饰符(如 th:valueth:actionth:href),是日常开发的首选;
  3. 专用属性修饰符语法更简洁,直接通过 th:属性名 赋值,无需嵌套表达式,提升模板可读性。