5.4 附加与前置

Thymeleaf也提供了th:attrappendth:attrprepend属性。它们会给既存的属性值附加(后缀)或者前置(前缀)求值的结果。

例如,你可能想要保存一个CSS类的名字,把它加入(不是设置,只是加入)上下文变量里的其中一个按钮。因为哪个特定的CSS类会被使用,取决于用户之前做了什么:

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

如果你处理这个模版,把变量cssStyle设置成了"warning",你将会得到:

  1. <input type="button" value="Do it!" class="btn warning" />

标准方言里也有两种特定的附加属性:th:classappendth:styleappend属性。它们用于给一个元素添加CSS类或样式片段,而不用重写既存的部分:

  1. <tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'">

(不用担心th:each属性。它是一个遍历属性。我们将在之后讨论。)