thymeleaf 中下拉列表
时间: 2023-10-14 15:24:43 浏览: 115
在 Thymeleaf 中创建下拉列表可以通过以下步骤实现:
1. 在 HTML 页面的表单中添加一个 select 元素。
2. 使用 Thymeleaf 的 th:each 属性迭代列表中的选项。
3. 使用 th:value 属性设置每个选项的值。
4. 使用 th:text 属性设置每个选项的文本。
5. 可以使用 th:selected 属性设置默认选中选项。
示例代码如下:
```html
<select name="fruit">
<option th:each="fruit : ${fruits}"
th:value="${fruit.id}"
th:text="${fruit.name}"
th:selected="${fruit.id == selectedId}"></option>
</select>
```
其中,`${fruits}` 是一个包含水果列表的模型属性,`selectedId` 是默认选中的水果 ID。在迭代过程中,使用 `fruit` 作为每个水果的迭代变量。使用 `${fruit.id}` 和 `${fruit.name}` 分别为每个选项设置值和文本。
注意:如果使用 Thymeleaf 的 Spring 表单绑定,可以使用 th:field 属性自动设置 select 元素的 name 和 id 属性。示例代码如下:
```html
<select th:field="*{fruit}">
<option th:each="fruit : ${fruits}"
th:value="${fruit.id}"
th:text="${fruit.name}"
th:selected="${fruit.id == selectedId}"></option>
</select>
```
其中,`${fruits}` 和 `selectedId` 是模型属性,`*{fruit}` 表示 Spring 表单绑定的字段名。使用 th:field 属性可以自动设置 select 元素的 name 和 id 属性。
阅读全文
相关推荐
















