using thymeleaf之七设置属性的值(th:attr/th:value/th:alt-title/th:attrappend/th:attrprepend/th:checked)

时间:2025-02-15 08:06:03

7.1 th:attr

用于设置其他属性的值,但不是所有属性的值都能设置,如text。

<form action="" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe me!" th:attr="value=#{}"/>
  </fieldset>
</form>

th:attr还可以同时设置多个属性的值,以逗号隔开

<img src="../../images/" 
     th:attr="src=@{/images/},title=#{logo},alt=#{logo}" />

7.2 th:alt-title

用于设置 alt 和title属性的值相同的两个属性。

<img src="../../images/" 
     th:src="@{/images/}" th:title="#{logo}" th:alt="#{logo}" />

用th:alt-title后:

<img src="../../images/" 
     th:src="@{/images/}" th:alt-title="#{logo}" />

7.3 th:attrappend和th:attrprepend

th:attrappend属性值前缀,例如一个标签的类名为a,想要变为“a b”,即增加一个类样式,可以使用此属性.

<input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />

th:attrprepend的用法则相反,
th:attrappend="class=${cssStyle+' '}"

7.4 th:checked设置复选框的值

此为布尔值属性之一,以后会详细介绍其他属性,在此先介绍th:checked。

(1)选中为:

<input type="checkbox" name="active" th:checked="true" />
(2)未选中为:

<input type="checkbox" name="noactive" th:checked="false" />
thymeleaf解析时不会设置th:checked属性,即解析后为

<input type="checkbox" name="noactive" />