鉴于将标签绑定到输入值是正确的,即:
<label for="username">Your name</label>
<input type="text" id="username" />
我希望 Thymeleaf 也将
for
字段添加到 label
中,与 id
中使用的 input
相匹配。它可能对此有支持,但显然让我失望了。
鉴于这样的事情:
<form action="#" th:action="@{/addAddress}" method="post" th:object="${address}">
<label th:for="*{street}">Street</label>
<input type="text" th:field="*{street}"/>
...
</form>
创建的 Html 输出就是这样(缺少
for
内的 label
字段。
<form action="/addAddress" method="post">
<label>Street</label>
<input type="text" id="street" name="street" value=""/>
thymeleaf 能否生成一个
for
字段在 label
中使用,与 id
中使用的 input
相匹配?
我知道我可以将
label
包裹在 input
周围,但我不想那样做。
您只需重载由
id
设置的 th:field
属性即可。
<form action="#" th:action="@{/addAddress}" method="post" th:object="${address}">
<label for="street">Street</label>
<input id="street" type="text" th:field="*{street}"/>
...
</form>
如果您担心 id 冲突,thymeleaf 有一堆 id 生成实用程序: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#ids
注意事实
th:field
的行为与其他百里香属性完全不同。它做了三件事:
value
属性设置为对象中街道字段的值(这并不罕见,与 th:value="*{street}"
id
和 name
html 属性设置为街道字段街道的 name(不是值)。这与 th:id="*{street}"
不同,后者将使用 field street 的值。