【发布时间】:2015-07-01 19:45:45
【问题描述】:
如你所知,input 组件有一个属性,checked 是否将复选框标记为默认启用。
<input type="checkbox" name="mycheckbox" checked="checked"/>
要默认禁用复选框,应声明checked 异常。是否可以通过 Thymeleaf 中的标志设置checked 属性?
【问题讨论】:
标签: html thymeleaf html-input
如你所知,input 组件有一个属性,checked 是否将复选框标记为默认启用。
<input type="checkbox" name="mycheckbox" checked="checked"/>
要默认禁用复选框,应声明checked 异常。是否可以通过 Thymeleaf 中的标志设置checked 属性?
【问题讨论】:
标签: html thymeleaf html-input
经过一番挖掘,我找到了解决方案。为此目的有th:checked 属性。
这行得通:
<input type="checkbox" name="mycheckbox" th:checked="${flag} ? 'checked'">
这失败了:
<input type="checkbox" name="mycheckbox" th:checked="${flag} ? 'checked' : ''">
如果 checked="" 设置为 input 组件,则标记为选中。此方法对自定义属性th:attr 也有效。考虑以下示例:
<p th:attr="customattr=${flag}?'attr'></p>
如果flag 为真,则替换为:
<p customattr="attr"></p>
如果flag 为假,则替换为:
<p></p>
【讨论】:
th:checked=${flag},对于checked属性更简洁
th:checked="${model.myField == null}"?
根据 thymeleaf 官方文档
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#fixed-value-boolean-attributes
th:checked 被认为是一个固定值的布尔属性。
<input type="checkbox" name="active" th:checked="${user.active}" />
user.active 应该是 boolean。
所以在你的情况下,它应该是 Andrea 提到的,
<input type="checkbox" name="mycheckbox" th:checked="${flag}" />
【讨论】:
您可以有条件地将选中的属性添加到百里香中的单选输入,如下所示:
<input type="radio" th:checked="${sales.sales_head.sales_type} == CREDIT" class="sales_type" value="CREDIT" name="sales_type" >
如果 sales_type 为 CREDIT,则将检查收音机。否则它将保持未选中状态。
【讨论】:
建议的解决方案都不适合我。
这个成功了:
th:checked="${#strings.equals(param.myRequestParameterXYZ, 'foobar')}"
【讨论】:
我遇到了根据属性的真值或假值在百里香中显示复选框(勾选标记开/关)的问题。我通过以下方式解决了。
控制器中的方法
@RequestMapping(value = "/test")
public String showCheckbox(Model model) {
boolean myBooleanVariable = false;
model.addAttribute("myBooleanVariable", myBooleanVariable);
return "sample-checkbox";
}
在 HTML 页面中:
<input type="checkbox" name="myBooleanVariable" th:checked="${myBooleanVariable}"/>
【讨论】:
如果你有一个作为模型表示的表单,比如 foo,bar 是你的表单和 foo 属性上的复选框(例如 foo.bar):
<form th:object="${foo}">
<input type="checkbox" th:field="*{bar}" th:value="*{bar}"></input>
</form>
...也可以使用并提供简洁的方法。
【讨论】: