【发布时间】:2019-01-07 10:21:01
【问题描述】:
我有一个使用 Thymeleaf 进行模板的 Spring MVC 应用程序。我正在使用枚举动态生成复选框。因此,如果我的枚举文件有 3 个值,它将生成 3 个复选框:
我的枚举文件:
public enum Foods {
PIZZA("Pizza"),
PASTA("Pasta"),
MAC_CHEESE("Mac and Cheese"),
ICE_CREAM("Ice Cream"),
BURGER("Burger"),
private String type;
Foods(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
这是我的复选框生成:
<label for="decision">What is your favorite food?</label>
<div id="decision" class="row" style="margin-top:1%;">
<div class="col-md-4" th:each="option : ${T(in.app.model.enums.Foods).values()}">
<div class="checkbox checkbox-custom checkbox-circle">
<input name="decision" type="checkbox" th:id="${option.toString()}" th:value="${option}" />
<label th:for="${option.toString()}" th:text="${option.type}"></label>
</div>
</div>
</div>
此代码将为每种食物类型生成 5 个复选框。所有工作到这里。我面临的问题是如何在读取保存的记录时设置选中的属性。
我正在通过模型视图控制器取回一个对象。该对象有一个食物属性,其值为所选食物类型的数组。
user = {
.
.
food : ["PIZZA", "BURGER", "PASTA"],
.
.
}
现在我想遍历这个数组,如果值匹配,则设置复选框。
我正在尝试做这样的事情:
<label for="decision">What is your favorite food?</label>
<div id="decision" class="row" style="margin-top:1%;">
<div class="col-md-4" th:each="option : ${T(in.app.model.enums.Foods).values()}">
<div class="checkbox checkbox-custom checkbox-circle">
<input
name="decision"
type="checkbox"
th:id="${option.toString()}"
th:value="${option}"
th:each="food : ${user.food}"
th:attr="checked = ${food} == ${option} ? 'checked'"
/>
<label th:for="${option.toString()}" th:text="${option.type}"></label>
</div>
</div>
</div>
我知道它错了(因为它不起作用),但我无法弄清楚如何循环两个数组以显示复选框并检查它们。
【问题讨论】:
-
您能否发布应用程序输出的内容,或 thymeleaf 中与之相关的任何错误?
标签: spring-mvc enums thymeleaf