spring-mvc - Thymeleaf:从数组中填充复选框
问题描述
我有一个使用 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>
我知道它是错误的(因为它不起作用),但我无法弄清楚如何遍历两个数组以显示复选框并检查它们。
解决方案
You might want to try using th:checked instead of th:attr if you can, so:
th:checked="${food == option.type}"
This post might also be helpful when looking into that. If you can't use th:checked, switching to the below statement should also work.
th:attr="checked=${food == option.type} ? 'checked'"
It also seems like you may run into some issues with checking this data due to case sensitivity while comparing, in which case this post might be helpful.
推荐阅读
- sql - 获取具有 JSONB 值的行,以及如果值不存在的行
- ionic-framework - 使用 PHPMailer 和 ionic 3 发送电子邮件
- c - Sys V ABI 规范(i386 和 AMD64)中描述的标准“函数调用序列”是否适用于静态 C 函数?
- jenkins - 如何同时在同一个项目(工作区)上运行多个 SonarQube 分析?
- javascript - 从 RN 中的 setTimeout 或 Alert 回调中调度 redux 操作时性能下降
- c# - StringBuilder - 是否应该只使用 Append 和 AppendLine 而不在参数中组合字符串?
- jquery - ID 不适用于动态添加的 td 内容
- ruby-on-rails - 无法加载此类文件 -- autoprefixer-rails (LoadError) | 导轨 5
- ios - 如何在其他应用程序的“打开方向”列表中添加我的自定义 iOS 地图应用程序?
- python - SAS中的proc格式相当于python