深色模式
5.5 固定值布尔属性
HTML 中有布尔属性的概念——这类属性无需设置具体值,只要属性存在,就表示其值为“true”;而在 XHTML 中,这类属性需要赋值为自身(即属性名和值相同)。
比如 checked 属性的写法:
html
<!-- HTML 写法:仅存在属性即表示 true -->
<input type="checkbox" name="option2" checked />
<!-- XHTML 写法:属性值必须等于属性名 -->
<input type="checkbox" name="option1" checked="checked" />Thymeleaf 的标准方言提供了专门的属性来处理这类布尔属性:它会通过计算一个条件表达式来决定是否设置该属性——如果表达式结果为 true,则将该属性设为其“固定值”(即 XHTML 规范的自身值,如 checked="checked");如果结果为 false,则不渲染该属性。
html
<!-- 若 ${user.active} 为 true,渲染为 checked="checked";为 false 则无 checked 属性 -->
<input type="checkbox" name="active" th:checked="${user.active}" />- 当
user.active = true时,输出:<input type="checkbox" name="active" checked="checked" />; - 当
user.active = false时,输出:<input type="checkbox" name="active" />。
标准方言中支持的固定值布尔属性列表
| th:async | th:autofocus | th:autoplay |
| th:checked | th:controls | th:declare |
| th:default | th:defer | th:disabled |
| th:formnovalidate | th:hidden | th:ismap |
| th:loop | th:multiple | th:novalidate |
| th:nowrap | th:open | th:pubdate |
| th:readonly | th:required | th:reversed |
| th:scoped | th:seamless | th:selected |
扩展示例
html
<!-- 禁用按钮:isSubmitDisabled 为 true 时添加 disabled 属性 -->
<button th:disabled="${isSubmitDisabled}">提交</button>
<!-- 下拉选项选中:item.id 等于 selectedId 时添加 selected 属性 -->
<select name="product">
<option th:each="item : ${products}"
th:value="${item.id}"
th:selected="${item.id == selectedId}">
[[${item.name}]]
</option>
</select>总结
- 布尔属性的核心逻辑:“存在即 true,不存在即 false”,Thymeleaf 无需手动赋值,只需通过条件表达式控制属性是否渲染;
- Thymeleaf 的布尔属性(如
th:checked/th:disabled)会自动适配 XHTML 规范,条件为 true 时赋值为属性自身(如checked="checked"); - 常用布尔属性优先使用 Thymeleaf 专用修饰符,避免手动写
th:attr="checked=${条件} ? 'checked' : null"这类冗余代码。
